Friday, February 17, 2012

Dynamic SQL Query

I have an array list of Branch_ID's; i need to select all records from 2 tables that have any of the branch id's in that array associated with them. How would I go about doing this?

Well in Dynamic SQL you could simply construct the query out ofsubstrings (create the appropriate IN (a, b, c,d) clause) but if youwanted to use a stored procedure you should take a look here:[http://odetocode.com/Articles/365.aspx
I use a similar technique to retrieve a number of records from a table based on a csv list being passed in. Works great.
|||To side-step dynamic SQL consider using XML and OpenXML to create a virtual table to join against. This way you can use Text without having to worry about tricky text manipulation and you don't have to worry about your array being too big to contain in a varchar. It's not perfect for performance but prob not far from dynamic SQL and without all those nasty injection attack worries.|||

Pass the select statement to the stored procedure as a parameter. Try something like this.
Create procedure yourProc

@.select_statement as varchar(200)

As

Declare @.sql as varchar(500)
Set @.sql = 'Select' + @.select_statement +
'FROM table1, table2'
EXEC(@.sql)

No comments:

Post a Comment