Having multiple values assigned to a single ADO.Net SqlClient parameter

那年仲夏 提交于 2019-12-11 18:31:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4994124/having-multiple-values-assigned-to-a-single-ado-net-sqlclient-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!