How to pass parameters to SQL script via Powershell
You could take advantage of sqlcmd's scripting variables. Those can be used in script file and are marked with $()
. Like so,
-- Sql script file
use $(db);
select someting from somewhere;
When calling sqlcmd
, use the -v
parameter to assign variables. Like so,
sqlcmd -S server\instance -E -v db ="MyDatabase" -i s.sql
Edit
Mind the Sql syntax when setting variables. Consider the following script:
DECLARE @dbName varchar(255)
SET @dbName = $(db)
select 'val' = @dbName
As passed to the Sql Server, it looks like so (Profiler helps here):
use master;
DECLARE @dbName varchar(255)
SET @dbName = foo
select 'val' = @dbName
This is, obviously invalid a syntax, as SET @dbName = foo
won't make much sense. The value ought to be within single quotes like so,
sqlcmd -S server\instance -E -v db ="'foo'" -i s.sql
Just in case someone else needs to do this... here is a working example.
Power Shell Script:
sqlcmd -S uk-ldn-dt270 -U sa -P 1NetNasdf£! -v db = "'DatabaseNameHere'" -i $scriptFile -b | Tee-Object -filepath $sqlLog
Note the -v switch to assign the variables
And here is the MS SQL:
USE MASTER
GO
if db_id($(db)) is null
BEGIN
EXEC('
RESTORE DATABASE ' + $(db) + '
FROM DISK = ''D:\DB Backup\EmptyLiveV5.bak''
WITH MOVE ''LiveV5_Data'' TO ''C:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\LiveV5_' + $(db) + '.MDF'',
MOVE ''LiveV5_Log'' To ''C:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\LiveV5_' + $(db) + '_log.LDF'', REPLACE,
STATS =10')
END
Note: You do not have to assign the scripting varible to a normal sql varible like this.
SET @dbName = $(db)
you can just use it in your sql code. - Happy coding.