将guids作为CSV字符串传递的存储过程

时间:2012-06-15 03:14:05

标签: sql-server-2008 tsql stored-procedures

调用存储过程

exec spBatchRequestsForRescreening @GuidList='''A2C4B17A-57A7-49A9-97A0-0000070D92F3'',''945FA383-17D4-4CCB-B8FD-00000A40E2DC'''

失败了 “从字符串转换为uniqueidentifier时转换失败。”

存储过程

ALTER PROC [dbo].[spBatchRequestsForRescreening] (@GuidList varchar(8000) )
AS BEGIN
    select *
    from DeniedPartyTransactions.dbo.DpsRequest
    with (nolock)
    where C1_PK in ( @GuidList )
END

以下声明有效。有没有办法用单引号宏替换Guids的CSV。

select * from DpsRequest
where c1_PK in ( 'A2C4B17A-57A7-49A9-97A0-0000070D92F3','945FA383-17D4-4CCB-B8FD-00000A40E2DC' ) 

更新:

以下工作。也许有更好的东西?

ALTER PROC [dbo].[spBatchRequestsForRescreening] (@GuidList varchar(7000) )
AS BEGIN
    DECLARE @SQL varchar(8000)
    SET @SQL = 
    'select *
    from DeniedPartyTransactions.dbo.DpsRequest
    with (nolock)
    where C1_PK in (' +  @GuidList + ')' ;
    EXEC(@SQL)    
END

1 个答案:

答案 0 :(得分:2)

创建拆分功能:

CREATE FUNCTION dbo.SplitGUIDs(@List NVARCHAR(MAX))
RETURNS TABLE
AS
   RETURN ( SELECT Item = CONVERT(UNIQUEIDENTIFIER, Item) FROM
       ( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
         FROM ( SELECT [XML] = CONVERT(XML, '<i>'
         + REPLACE(@List, ',', '</i><i>') + '</i>').query('.')
           ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
       WHERE Item IS NOT NULL
   );
GO

然后你可以这样改变你的程序:

ALTER PROCEDURE [dbo].[spBatchRequestsForRescreening] 
    @GuidList varchar(8000)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT d.* -- probably meant to list specific columns
      FROM dbo.DeniedPartyTransactions AS d
      INNER JOIN dbo.SplitStrings(@GuidList) AS s
      ON d.C1_PK = s.Item;
END
GO

(您不必包含所有额外的单引号。)

你也可以考虑一个表值参数,你可以在我的答案中看到一个例子:

Parameters to the EXISTS clause in a stored procedure