views:

1039

answers:

4

hi friends,

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.

+1  A: 

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.

csl
ya i have tried that , same problem im gettingConversion failed when converting the varchar value to data type int
Ranjana
+4  A: 
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

AdaTheDev
+2  A: 

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;
edosoft
ya this works out for me!!! thank you guys
Ranjana
but will you clear me about these two lines . 'OUTPUT'SET @ParmDefinition = N'@CountOUT int OUTPUT';and @CountOUT=@count OUTPUT;
Ranjana
bear in mind possible SQL injection issues, per my answer
AdaTheDev
sp_executesql takes a list of parameters, this is defined in the variable @ParmDefinition here. Output means the variable if 'filled' with data in the query and can be used when the query is finished.
edosoft
+1  A: 

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

Frank Kalis