我有这个问题:
declare @docId as varchar(36)
declare @totalId AS VARCHAR(500)
declare @C5 as int
declare @bool as bit
set @bool =1
set @docId='fba18752-1a70-4413-bc3f-9390eaf8a7ef'
set @totalId='''95B3F02C-8EBD-402E-9721-268A02830678'''+','+'''0211CFA9-1957-4C46-A6BE-16F7B5D8C50F'''
print @totalId
SELECT @C5=COUNT(*) FROM tblSend WHERE senDocId= @docId AND senReceiverDepartmentId IN (@totalId) AND senStatus in (3110,3125,3121) AND senReadDocument IN (0,2)
并有以下错误:
Msg 8169, Level 16, State 2, Line 15
Conversion failed when converting from a character string to uniqueidentifier.
但是当我把@totalId值而不是它的变量时,它会像这样返回:
SELECT @C5=COUNT(*) FROM tblSend WHERE senDocId= @docId AND senReceiverDepartmentId IN ('95B3F02C-8EBD-402E-9721-268A02830678','0211CFA9-1957-4C46-A6BE-16F7B5D8C50F') AND senStatus in (3110,3125,3121) AND senReadDocument IN (0,2)
为什么?
答案 0 :(得分:0)
因为IN
要求单个或逗号分隔的值与列值匹配。您在IN
内证明的值为'SomeX,SomeY'
。 SQL Server试图在'SomeX,SomeY'
中查找senReceiverDepartmentId
值,在此过程中,它尝试将'SomeX,SomeY'
转换为GUID(源列数据类型)。这导致无效的转换错误。
您希望在 IN
中使用 'SomeX'
,'SomeY'
您实际使用的是 'SomeX,SomeY'
尝试使用表变量并在其中插入ID并将其与IN
组合使用。
declare @docId as varchar(36)
DECLARE @totalId AS VARCHAR(500)
declare @C5 as int
declare @bool as bit
set @bool =1
set @docId='fba18752-1a70-4413-bc3f-9390eaf8a7ef'
DECLARE @totalIds TABLE(id varchar(100))
INSERT INTO @totalIds
VALUES
('95B3F02C-8EBD-402E-9721-268A02830678'),
('0211CFA9-1957-4C46-A6BE-16F7B5D8C50F')
print @totalId
SELECT @C5=COUNT(*)
FROM tblSend
WHERE senDocId= @docId
AND senReceiverDepartmentId IN (select id from @totalIds)
AND senStatus in (3110,3125,3121) AND senReadDocument IN (0,2)
希望这是有道理的。