1

存储过程的调用

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

失败并显示“从字符串转换为唯一标识符时转换失败。”

存储过程

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

下面的陈述有效。有没有办法用单引号对 Guid 的 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
4

1 回答 1

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

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

您还可以考虑使用表值参数,您可以在我的答案中看到一个示例:

存储过程中 EXISTS 子句的参数

于 2012-06-15T03:51:01.953 回答