SQL数据类型转换错误

时间:2013-12-24 06:52:55

标签: sql sql-server sql-delete type-conversion

我正在尝试这段代码:

DECLARE @testID varchar(max)
set @testID = '1,2,3'

Delete from [Test] where [Test_ID] in (@testID)

但是我收到了一个错误:

  

将varchar值'1,2,3'转换为数据类型int时,转换失败。

任何人都可以帮忙......

5 个答案:

答案 0 :(得分:1)

您的查询编译为

Delete from [Test] where [Test_ID] in ('1,2,3')

但它应该是

Delete from [Test] where [Test_ID] in ('1','2','3')

您不能将单个字符串放入IN子句中。使用单独的值。

答案 1 :(得分:1)

你试过这个吗?

declare @testID varchar(max)
set @testID =1,2,3
set @testID='delete from [Test] where [Test_ID] in('+@testID+')'
exec(@testID)

答案 2 :(得分:0)

试试这个:

DECLARE @testID VARCHAR(MAX);
SET @testID = '1,2,3';
DELETE FROM [Test] WHERE ',' + @testID + ',' LIKE '%,' + [Test_ID] + ',%'

DELETE FROM [Test] WHERE [Test_ID] IN (1,2,3)

答案 3 :(得分:0)

您的删除查询应该像

Delete From [Test] Where [Test_ID] in (1,2,3) 

但您无法,因为您的参数是csv格式。所以你必须列出一个int列表。并删除此列表中包含的记录。

试试这个:

declare @xml xml = N'<root><r>' + replace(@testID ,',','</r><r>') + '</r></root>';
Delete From [Test] Where [Test_Id] in (
select * from(select t.value('.','int') as ID from @xml.nodes('//root/r') as a(t)) r

)

答案 4 :(得分:0)

另一种可能的方式......请参考以下内容......

  DECLARE @testID varchar(max)
 DECLARE @testExec varchar(max)
set @testID = '1,2,3'
Set @testExec = 'Delete from IMPCT_INTAKE_REQ where IMPCT_INTAKE_ID in ('+@testID+')'
print @testExec
execute (@testExec)