How do I call a SQL Server stored procedure from PowerShell?

前端 未结 6 1347
悲&欢浪女
悲&欢浪女 2020-12-07 17:04

I have a large CSV file and I want to execute a stored procedure for each line.

What is the best way to execute a stored procedure from PowerShell?

6条回答
  •  太阳男子
    2020-12-07 17:21

    Here is a function I use to execute sql commands. You just have to change $sqlCommand.CommandText to the name of your sproc and $SqlCommand.CommandType to CommandType.StoredProcedure.

    function execute-Sql{
        param($server, $db, $sql )
        $sqlConnection = new-object System.Data.SqlClient.SqlConnection
        $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db 
        $sqlConnection.Open()
        $sqlCommand = new-object System.Data.SqlClient.SqlCommand
        $sqlCommand.CommandTimeout = 120
        $sqlCommand.Connection = $sqlConnection
        $sqlCommand.CommandText= $sql
        $text = $sql.Substring(0, 50)
        Write-Progress -Activity "Executing SQL" -Status "Executing SQL => $text..."
        Write-Host "Executing SQL => $text..."
        $result = $sqlCommand.ExecuteNonQuery()
        $sqlConnection.Close()
    }
    

提交回复
热议问题