错误将varchar值转换为int时转换失败

时间:2014-10-30 14:23:37

标签: sql sql-server tsql int varchar

我的代码出现以下错误:

  

转换varchar值时转换失败'(CASE WHEN   ROW_NUM ='到数据类型int。

我做错了什么?

DECLARE @N          INT = 6, 
        @I          INT = 0, 
        @SQL        NVARCHAR(MAX) 


BEGIN
 SET @SQL = '(CASE WHEN ROW_NUM = '+@I+'THEN problem ELSE NULL END) ';
 SET @I = @I+1;
END

EXEC SP_EXECUTESQL 
  @SQL 

2 个答案:

答案 0 :(得分:1)

根据您发布的代码,您将缺少SELECT语句和FROM子句。您还假设您有一个名为ROW_NUM的列和一个名为problem的列:

DECLARE @N          INT = 6, 
        @I          INT = 0, 
        @SQL        NVARCHAR(MAX) 


BEGIN

  SET @SQL = 'SELECT CASE WHEN ROW_NUM = '+CAST(@I as VARCHAR(10))+' 
  THEN problem ELSE NULL END FROM MyTable';
 SET @I = @I+1;

END
print @SQL
EXEC SP_EXECUTESQL @SQL 

但是,看起来您还试图在没有实际定义WHILE的情况下执行WHILE循环,您可以这样做:

DECLARE @N          INT = 6, 
        @I          INT = 0, 
        @SQL        NVARCHAR(MAX) 

WHILE @I <= @N   -- new code

 BEGIN
  SET @SQL = 'SELECT CASE WHEN ROW_NUM = '+CAST(@I as VARCHAR(10))+' THEN problem ELSE NULL END FROM MyTable';
  SET @I = @I+1;
  PRINT @SQL
  EXEC SP_EXECUTESQL @SQL 
 END

我认为你实际上在寻找这样的东西:

SELECT 'Problem', *
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY ROW_NUM) rn FROM MyTable) s
WHERE rn <> ROW_NUM

带有虚拟数据的示例:

DECLARE @MyTable TABLE (ROW_NUM INT, SomeData VARCHAR(5))
INSERT INTO @MyTable (ROW_NUM, SomeData) VALUES (1, 'foo')
INSERT INTO @MyTable (ROW_NUM, SomeData) VALUES (2, 'zip')
INSERT INTO @MyTable (ROW_NUM, SomeData) VALUES (3, 'yak')
INSERT INTO @MyTable (ROW_NUM, SomeData) VALUES (5, 'lop')
INSERT INTO @MyTable (ROW_NUM, SomeData) VALUES (6, 'cow')
INSERT INTO @MyTable (ROW_NUM, SomeData) VALUES (7, 'moo')


SELECT 'Problem', *
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY ROW_NUM) rn FROM @MyTable) s
WHERE rn <> ROW_NUM

答案 1 :(得分:0)

试试这个:您需要Cast int to varchar并尝试执行Printed SQL以获取错误探测

DECLARE @N          INT = 6, 
        @I          INT = 0, 
        @SQL        NVARCHAR(MAX) 


BEGIN

  SET @SQL = '(CASE WHEN ROW_NUM = '+CAST(@I as VARCHAR(10))+' 
  THEN problem ELSE NULL END) ';
 SET @I = @I+1;
END
print @SQL
EXEC SP_EXECUTESQL @SQL