Skip to content
Advertisement

Set variable value to array of strings

I want to set a variable as a string of values. E.g.

declare @FirstName char(100)
select @FirstName = 'John','Sarah','George'

SELECT * 
FROM Accounts
WHERE FirstName in (@FirstName)

I’m getting a syntax error in the line select @FirstName = 'John','Sarah','George':

Incorrect syntax near ','

Is there any way I can set the variable with many values?

Advertisement

Answer

You’re trying to assign three separate string literals to a single string variable. A valid string variable would be 'John, Sarah, George'. If you want embedded single quotes between the double quotes, you have to escape them.

Also, your actual SELECT won’t work, because SQL databases won’t parse the string variable out into individual literal values. You need to use dynamic SQL instead, and then execute that dynamic SQL statement. (Search this site for dynamic SQL, with the database engine you’re using as the topic (as in [sqlserver] dynamic SQL), and you should get several examples.)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement