Guest User

Untitled

a guest
Feb 23rd, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #
  2. # CSV File Dumper (Sxxx)
  3. # Tom Kober 2018-01-18
  4. #
  5. # Dumps all tables from specified SQL Server database to CSV
  6. # $tablequery = "SELECT name from sys.tables"
  7. #
  8. # If table query is a fixed value, like below, only table is exported
  9. # $tablequery = "SELECT 'YOURVIEWORTABLENAME'"
  10. #
  11. $server = "YOUR SERVER"
  12. $database = "YOUR DATABASE"
  13. $tablequery = "SELECT name from sys.tables"
  14.  
  15. #Declare connection
  16. $connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
  17. $connectionString = [string]::Format($connectionTemplate, $server, $database)
  18. $connection = New-Object System.Data.SqlClient.SqlConnection
  19. $connection.ConnectionString = $connectionString
  20.  
  21. $command = New-Object System.Data.SqlClient.SqlCommand
  22. $command.CommandText = $tablequery
  23. $command.Connection = $connection
  24.  
  25. #Load the tables in a dataset
  26. $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  27. $SqlAdapter.SelectCommand = $command
  28. $DataSet = New-Object System.Data.DataSet
  29. $SqlAdapter.Fill($DataSet)
  30. $connection.Close()
  31.  
  32.  
  33. # Loop through all tables and export a CSV of the Table Data
  34. foreach ($Row in $DataSet.Tables[0].Rows)
  35. {
  36. $queryData = "SELECT * FROM [$($Row[0])]"
  37.  
  38. #Specify the output location of your dump file
  39. $extractFile = "D:\$($Row[0]).csv"
  40.  
  41. $command.CommandText = $queryData
  42. $command.Connection = $connection
  43.  
  44. $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  45. $SqlAdapter.SelectCommand = $command
  46. $DataSet = New-Object System.Data.DataSet
  47. $SqlAdapter.Fill($DataSet)
  48. $connection.Close()
  49.  
  50. $DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation -Delimiter ';' -Encoding OEM
  51. }
Add Comment
Please, Sign In to add comment