开发者

Conversion failed when converting the nvarchar value to int

开发者 https://www.devze.com 2022-12-18 01:18 出处:网络
Declare @count nvarchar(max) set @c开发者_开发百科ount =\'select COUNT(*) from \'+ @tablename+\'\'

Declare @count nvarchar(max)

set @c开发者_开发百科ount ='select COUNT(*) from '+ @tablename+''

if( @count =0 )
begin 
  print 'fail'
end
else
begin
  print 'success'
end
end

the @count variable is not getting the value 0. it shows the error as

Conversion failed when converting the nvarchar value 'select COUNT(*) from tablename' to data type int.


DECLARE @Count INTEGER
DECLARE @nSQL NVARCHAR(1000)
SET @nSQL = 'SELECT @Count = COUNT(*) FROM ' + @tablename
EXECUTE sp_executesql @nSQL, N'@Count INTEGER OUT', @Count OUT

-- Now check @Count

Be extra careful with dynamic sql like this, as you open yourself up to sql injection. So make sure @tablename is sanitized.

One check to be safe would be something like this, by making sure the table exists using a parameterised query before attempting the dynamic query:

DECLARE @Count INTEGER
DECLARE @nSQL NVARCHAR(1000)
SET @nSQL = 'IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=@TableName) 
    SELECT @Count = COUNT(*) FROM ' + @tablename + '
ELSE
    SELECT @Count = -1'

EXECUTE sp_executesql @nSQL, N'@TableName NVARCHAR(128), @Count INTEGER OUT', @TableName, @Count OUT

If @Count then comes out at -1, you know it's because the tablename is invalid

Edit:
Reference to sp_executesql is here


This should work:

DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @count int

SET @SQLString = N'SELECT @CountOUT = COUNT(*) FROM ' + @tablename;
SET @ParmDefinition = N'@CountOUT int OUTPUT';

EXECUTE sp_executesql @SQLString, @ParmDefinition, @CountOUT=@count OUTPUT;

SELECT @count;


Check out Erland's standard article on Dynamic SQL. You're also a "victim" of Data Type Precedences


Try declaring @count as an int:

DECLARE @count AS INT
SELECT @count = COUNT(*) FROM YourTable

The problem is that if you do

SELECT @countAsString = 'SELECT ...'

then @countAsString (being a string) will not hold the result of the query, but the string itself.

Use EXEC to actually execute a dynamically created query.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号