I wish to run an SQL select statement similar to this
SELECT * FROM CatalogueItems WHERE id IN (1,10,15,20);
using ADO.Net SqlClient style @name parameters. I've tried using a stored SQL strings
SELECT * FROM CatalogueItems WHERE id IN (@Ids)
and then in my C# code
SqliteCommand command;
//...
//returns 0 results
command.Parameters.Add("@Ids", null).Value = "1,10,15,20";
//returns 0 results
command.Parameters.Add("@Ids", DbType.String).Value = "1,10,15,20";
//returns 1 or more results
command.Parameters.Add("@Ids", null).Value = "1";
returns an empty result set, yet the individual string parameters return results.
Is this query support? Is there another DBType I should be using?
Thanks.
You can't do that. A SQL-Server parameter must be a single value.
But you could have a look here to build the parameter list dynamically.
Edit: if using SQl-Server >=2008 you could use Table-valued parameters as suggested in this answer. It's new to me, but i'm on 2005 unfortunately.
Another option would be to create a user-defined-function that returns a table from your csv-string as this:
CREATE FUNCTION [dbo].[Split]
(
@ItemList NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @IDTable TABLE (Item VARCHAR(50))
AS
BEGIN
DECLARE @tempItemList NVARCHAR(MAX)
SET @tempItemList = @ItemList
DECLARE @i INT
DECLARE @Item NVARCHAR(4000)
SET @tempItemList = REPLACE (@tempItemList, ' ', '')
SET @i = CHARINDEX(@delimiter, @tempItemList)
WHILE (LEN(@tempItemList) > 0)
BEGIN
IF @i = 0
SET @Item = @tempItemList
ELSE
SET @Item = LEFT(@tempItemList, @i - 1)
INSERT INTO @IDTable(Item) VALUES(@Item)
IF @i = 0
SET @tempItemList = ''
ELSE
SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i)
SET @i = CHARINDEX(@delimiter, @tempItemList)
END
RETURN
END
Then you could use this function to split your ID's and join it with your result set.
Such as this:
SELECT CatalogueItems .*
FROM CatalogueItems INNER JOIN
dbo.Split(@Ids, ',') AS IdList ON CatalogueItems.ID = IdList.Item
In this case one string-parameter for all ID's is sufficient.