Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic SQL Table Variable 1

Status
Not open for further replies.

Elegabalus

Programmer
Joined
Jan 13, 2005
Messages
71
Location
CA
I've got a query that is dynamic sql. One of the variables (PersonID) that gets passed into the query is a comma delimited string that provides a list of PersonIDs (i.e., the string would be: "1,2,3,4,5,6").

I want to build the WHERE clause dynamically, with the sql similar to: WHERE PersonID in (1,2,3,4,5,6). I know this is not possible directly, so I'm trying to use the Split UDf mentioned here:
Some code:

Code:
SELECT @sql = 'Select * FROM Table1'

SELECT @sql = @sql + ' WHERE PersonID IN (SELECT Value FROM dbo.Split(@List,','))'

However, every time I try to do this, I get the following error:
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.[/color red]

Apparently you can't reference a UDF in a dynamic query? I've tried doing this with table variables instead, but I get the same problem...can't assign values in the sql.

Is there a way to use a UDF in a dynamicly built sql query?

Any helps is appreciated.
 
Try this:

SELECT @sql = 'Select * FROM Table1 WHERE PersonID IN (' + @List+')'

exec(@sql)

If your string is already in the format - 1,2,3,4,5,6 you don't need to split it since the same format works for the IN operator.


rsshetty.
It's always in the details.
 
Ah, great, thanks...I was thinking too much with regular SQL, and passing in a comma delimited list doesn't work with that.

Monday mornings. :-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top