I need to pass an array of "id's" to a stored procedure, to delete all rows from the table EXCEPT the rows that match id's in the array.
How can I do it in a most simple way?
I need to pass an array of "id's" to a stored procedure, to delete all rows from the table EXCEPT the rows that match id's in the array.
How can I do it in a most simple way?
this is the best source:
http://www.sommarskog.se/arrays-in-sql.html
create a split function using the link, and use it like:
I prefer the number table approach
This is code based on the above link that should do it for you...
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
use this function to split your string, which does not loop and is very fast:
What about using the XML data type instead of passing an array. I find that a better solution and works well in SQL 2005
In SQL Server 2016 you can wrap array with [ ] and pass it as JSON see http://blogs.msdn.com/b/sqlserverstorageengine/archive/2015/09/08/passing-arrays-to-t-sql-procedures-as-json.aspx
You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.
I'd consider passing your IDs as an XML string, and then you could shred the XML into a temp table to join against, or you could also query against the XML directly using SP_XML_PREPAREDOCUMENT and OPENXML.