Wednesday, 5 October 2016

POWERSHELL: SQL Powershell script for table creation in database

[string] $Server= "database server name"
[string] $Database = "data base name"

[string] $cmdText = $("BEGIN TRY " +
"CREATE TABLE [dbo].[table_name]( [SAPID] [nvarchar](50) NULL, [Exception] [bit] NULL) " +
"END TRY  " +
"BEGIN CATCH  " +
      "print 'WARNING: ALREADY [table_name] TABLE EXIST'" +
"END CATCH  ")


$sqlConnection = new-object System.Data.SqlClient.SqlConnection $(“server={0};database={1};Integrated Security=sspi” -f $Server,$Database)


$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.connection = $sqlConnection
$Command.commandtext = $cmdText

$sqlConnection.Open()

$Command.executescalar()

$sqlConnection.Close()



No comments:

Post a Comment