Sql-server – Conversion failed when converting the nvarchar value to int

sql serverstored-procedures

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.

Best Answer

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

Related Topic