0

I am trying to pass server names in sql script , but its not working. Please help

SQL Script patch_report.sql, I am running via powershell giving error

SELECT * from table where server in ('$(trimsqlstr)')

Error

Msg 102,level Level 15, State 1, Server DBserver, Line 1
Incorrect syntax near 'server1'.
$DB_server = 'DBserver'
$serverName = "server1
server2
server3
"
$serverName = $serverName -split "\n" | foreach {$_.ToString().TrimEnd()}
$trimsqlstr = foreach($server in $serverName){
if ($serverName.Indexof($server) -eq $($serverName.Length-1)){
"'$Server'"
} else {
"'$Server',"
}

SQLCMD.exe -v trimsqlstr = "$($trimsqlstr)" -E -S $DB_server -W -i patch_report.sql

I am expecting it to result like this

SELECT * from table where server in ('server1','server2','server3')
1
  • my code was not working because it had wrong syntax , I was wrapping ('$(trimsqlstr)') in "'" , I corrected it to ($trimsqlstr) and it worked Commented Apr 5, 2019 at 11:37

2 Answers 2

2

The accepted answer is an excellent solution, I just want to point you towards the -join operator.

The -join operator is very practical for joining members of an array to a string.

You can do something like this:

$serverNames = "server1
server2
server3
"

$serverNameArray = $serverNames -split "\n" | foreach {$_.ToString().TrimEnd()} | Where-Object {$_} | foreach {"'$_'"}
$whereClause = $serverNameArray -join ','
$selectQuery = "SELECT * from table where server in ($whereClause)"

Where-Object {$_} is removing the empty elements.

Sign up to request clarification or add additional context in comments.

1 Comment

You could shorten further: (($serverNames -split "\n").Trim() -ne ''| ForEach-Object{"'$_'"}) -join ','
1

You may use below code:

$DB_server = 'DBserver'
$serverName = "server1
server2
server3
"

$serverName = $serverName -split "\n" | foreach {$_.ToString().TrimEnd()}
ForEach($server in $serverName) 
{
$serverstring = $serverstring+"'"+$server+"'"+","
}
$trimsqlstr = $serverstring.Substring(0, $serverstring.Length-4)

And then use $trimsqlstr in query like below

SELECT * from table where server in ($trimsqlstr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.