Innova
Innova

Reputation: 4981

Conversion failed when converting the nvarchar value to int

Declare @count nvarchar(max)

set @count ='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.

Upvotes: 3

Views: 21202

Answers (4)

AdaTheDev
AdaTheDev

Reputation: 147374

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

Upvotes: 5

Frank Kalis
Frank Kalis

Reputation: 1352

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

Upvotes: 2

edosoft
edosoft

Reputation: 17281

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;

Upvotes: 3

csl
csl

Reputation: 11368

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.

Upvotes: 1

Related Questions