I need to call a stored procedure and pass arguments in from Powershell. I think the best option is to use sqlcmd.exe but I'm not sure how to pass arguments to the stored proc using this tool.
Asked
Active
Viewed 4.8k times
2 Answers
18
sqlcmd.exe supports variable substitution and parameters via the /v
argument, see Using sqlcmd with Scripting Variables. For example:
sqlcmd -E -d <mydb> -Q "exec usp_myproc @variable=$(myparam)" /v myparam=1
will invoke the procedure passing the value 1 to the script to be substituted for the variable $(myparam)
. Note that sqlcmd variable substitution is a string replacement of $(variable)
which occurs in sqlcmd, befor the batch (request) is sent to the SQL Server.

Remus Rusanu
- 288,378
- 40
- 442
- 569
-
Thanks, that helps a lot. It should be a lower-case 'v' so I corrected that for you, otherwise good. – Martin Doms Jun 19 '11 at 23:19
4
The Invoke-Sqlcmd cmdlet lets you run your sqlcmd script files in a Windows PowerShell environment. Much of what you can do with sqlcmd can also be done using Invoke-Sqlcmd.
Example:
$myparam = "..."
Invoke-Sqlcmd -Query "EXEC sp_myproc $myparam" -ServerInstance "MyComputer\MyInstance"

Aleksey Cherenkov
- 1,405
- 21
- 25