存储过程选择多个记录ID

时间:2015-02-13 09:48:50

标签: c# asp.net sql-server sql-server-2008 stored-procedures

我有一组记录ID(x,y,z,..),它们作为字符串值传递给存储过程。我的存储过程是:

CREATE PROCEDURE [dbo].[Sp_Getvalue](@recordId varchar(30)) 
AS
BEGIN    
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    select  
    x.record_Id,
    x.name,
    x.address from dbo.tblvalue x where x.record_Id in (@recordId)
END

中的代码

var obj = context.Sp_Getvalue(value);

我收到错误

  

System.Data.Entity.dll中发生了'System.Data.EntityCommandExecutionException'类型的异常,但未在用户代码中处理

2 个答案:

答案 0 :(得分:0)

您不能直接在IN子句中使用该参数 请查看我使用SQL split string function

的语法
CREATE PROCEDURE [dbo].[Sp_Getvalue](@recordId varchar(30)) 
AS
BEGIN    
    SET NOCOUNT ON;

    select  
        x.record_Id,
        x.name,
        x.address 
    from dbo.tblvalue x 
    where 
        x.record_Id in (
            select val from dbo.split(@recordId,',')
        )
END

您可以从此处复制拆分功能代码:http://www.kodyaz.com/articles/t-sql-convert-split-delimeted-string-as-rows-using-xml.aspx 并在目标数据库上创建

答案 1 :(得分:0)

您不能直接在IN子句中使用逗号分隔值,也不需要为此创建任何函数。有两种方法可以做到这一点

<强> 1。使用Dynamic Sql根据@recordId

中的值获取记录
CREATE PROCEDURE [dbo].[Sp_Getvalue](@recordId varchar(30)) 
AS
BEGIN    
SET NOCOUNT ON;

DECLARE @query NVARCHAR(MAX)
SET @query = 'INSERT INTO TABLETOINSERT(COL,COL2,COL3)
              SELECT record_Id,name,address 
              FROM tblvalue 
              WHERE record_Id IN('+@recordId+')' 

EXEC SP_EXECUTESQL @query

END

如果您不想插入,只想要select语句,请删除 来自动态sql的INSERT INTO TABLETOINSERT(COL,COL2,COL3)

<强> 2。使用XML格式将逗号分隔值拆分为行并使用IN

CREATE PROCEDURE [dbo].[Sp_Getvalue](@recordId varchar(30)) 
AS
BEGIN    
SET NOCOUNT ON;


INSERT INTO TABLETOINSERT(COL1,COL2,COL3)
SELECT record_Id,NAME,[ADDRESS]
FROM tblvalue
WHERE record_Id IN
(
    -- Convert comma separated values to rows
    SELECT LTRIM(RTRIM(Split.a.value('.', 'VARCHAR(100)'))) 'KeyWords' 
    FROM  
    (        
         SELECT CAST ('<M>' + REPLACE(@recordId, ',', '</M><M>') + '</M>' AS XML) AS Data      
    ) AS A 
    CROSS APPLY Data.nodes ('/M') AS Split(a)
)

END