2

I'm trying to run the following Dynamic SQL statement:

@Tbl, @Fld, and @LookupValue have all been set according to Table to search, Field (Or Column) to search and column value to compare.

DECLARE @Sql AS VARCHAR(500)
SET @Sql = 'SELECT COUNT(*) 
            FROM ' + @Tbl +  
            ' WITH (NOLOCK) 
            WHERE ' + @Fld + ' = ''' + @LookupValue + ''''

EXEC(@Sql)

I want to store the result into a variable so I can check to see if there are any returned rows. This statement is in the middle of a WHILE construct that is checking several tables and fields.

If records are found, then I want to display:

SET @Sql = 'SELECT ' + @Fld +
           ' FROM ' + @Tbl + 
           ' WITH (NOLOCK) 
           WHERE ' + @Fld + ' = ''' + @LookupValue + ''''

EXEC(@Sql)
3
  • you need to use temporary table to store the count value Commented Nov 14, 2014 at 18:50
  • @RADAR, have to be SQL Server since there is no NOLOCK table hint in MySQL. Commented Nov 14, 2014 at 18:51
  • @Rahul, yes you are right. Commented Nov 14, 2014 at 18:54

2 Answers 2

3

Yes, you can store it in a typed variable and use sp_executesql like

DECLARE @Sql AS NVARCHAR(500);
DECLARE @cnt INT;

SET @Sql = 'SELECT @cnt = COUNT(*) 
            FROM ' + @Tbl +  
            ' WITH (NOLOCK) 
            WHERE ' + @Fld + ' = ''' + @LookupValue + '''';

EXEC sp_executesql @Sql, N'@cnt INT OUTPUT', @cnt OUTPUT;

SELECT @cnt;
Sign up to request clarification or add additional context in comments.

Comments

-1

you can create a temporary table and store the count value.

if object_id('tempdb.#mycount')  is null 
create table #mycount ( countVal int);

DECLARE @Sql AS VARCHAR(500)
SET @Sql = 'INSERT INTO #mycount 
            SELECT COUNT(*) 
            FROM ' + @Tbl +  
            ' WITH (NOLOCK) 
            WHERE ' + @Fld + ' = ''' + @LookupValue + ''''

EXEC(@Sql)

select countVal from #mycount


-- once the temp table usage is done, you can delete it
drop table #mycount

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.