I have a relation mapping table like this:
attributeid bigint
productid bigint
To clean relations that are not used any more, I want to delete all recors where productid = x and attributeid not in (@includedIds), like the following example:
@attributetypeid bigint, @productid bigint, @includedids varchar(MAX) DELETE FROM reltable WHERE productid = @productid AND attributetypeid = @attributetypeid AND attributeid NOT IN (@includedids);
When running the SQL with the includedids param containing more than 1 id – like this: 25,26 – I get a SqlException saying:
Error converting data type varchar to bigint.
And that is of course due to the , in that varchar(max) param…
How should I construct my delete statement to make it work?
Run that script in your SQL Server database to create the function ListToTable. Now, you can rewrite your query like so:
Where @includedids is a comma delimited list that you provide. I use this function all the time when working with lists. Keep in mind this function does not necessarily sanitize your inputs, it just looks for character data in a comma delimited list and puts each element into a record. Hope this helps.