Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

IF statement execution dependant on record count

Posted on 2006-06-18
10
Medium Priority
?
312 Views
Last Modified: 2008-02-01

I want to perform a series of actions on a table, but only if there are records in the table.

The table name will eventually be passed as parameter to the stored procedure, so the table name in the SELECT COUNT statement can change.

I'm struggling with the syntax and would appreciate some help.  I'm getting the following error:

Server: Msg 137, Level 15, State 2, Line 17
Must declare the variable '@tableName'.

I have declared the variable so I must be doing something else wrong.  Does anyone have any suggestions on how to fix this, or perhaps a better way to achieve the same thing?

Code being used:

DECLARE @type int, @tableName varchar(200), @numRecords int

SET @type = 7

IF @type = 7
BEGIN
    SET @tableName = 'table1'
END
ELSE
BEGIN
   SET @tableName = 'table2'
END

SELECT @numRecords= COUNT(*) FROM @tableName

-- only try and transfer records if some exist
IF (@numRecords) > 0
BEGIN
      PRINT 'There are records in the table'
END
0
Comment
Question by:ian_r
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 4

Expert Comment

by:indu_mk
ID: 16929495
Replace SELECT @numRecords= COUNT(*) FROM @tableName
with
declare @sql varchar(8000)
set @sql = 'SELECT @numRecords= COUNT(*) FROM ' + @tableName
exes(@sql)
0
 
LVL 33

Expert Comment

by:hongjun
ID: 16929496
Try this

DECLARE @type int, @tableName varchar(200), @numRecords int
Declare @SQL varchar(255)

SET @type = 7

IF @type = 7
BEGIN
    SET @tableName = 'table1'
END
ELSE
BEGIN
   SET @tableName = 'table2'
END

Set @SQL = 'SELECT @numRecords = COUNT(*) FROM [' + @tableName + ']'
Execute (@SQL)

-- only try and transfer records if some exist
IF (@numRecords) > 0
BEGIN
     PRINT 'There are records in the table'
END



hongjun
0
 
LVL 4

Expert Comment

by:indu_mk
ID: 16929503
sorry for the typo, its exec not exes
0
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 

Author Comment

by:ian_r
ID: 16929536
Thanks.  The two suggestions look the same to me, and I've just tried the code that hongjun supplied, but I'm now getting the error:

Server: Msg 137, Level 15, State 1, Line 1
Must declare the variable '@numRecords'.

Which is strange because @numRecords is declared.  I'll continue to play around with it, unless anyone know's why it's failing?

Maybe I've just been staring at it for too long...
0
 
LVL 33

Expert Comment

by:hongjun
ID: 16929601
Try this

DECLARE @type int, @tableName varchar(200)
Declare @SQL varchar(255)

SET @type = 7

IF @type = 7
BEGIN
    SET @tableName = 'table1'
END
ELSE
BEGIN
   SET @tableName = 'table2'
END

Execute ('
      Declare @numRecords int
      SELECT @numRecords=COUNT(*) FROM ' + @tableName +
      '-- only try and transfer records if some exist
      IF (@numRecords) > 0
      BEGIN
          PRINT ''There are records in the table''
      END
'
)
0
 
LVL 4

Accepted Solution

by:
indu_mk earned 100 total points
ID: 16929604
DECLARE @type int, @tableName varchar(200)
SET @type = 7

IF @type = 7
BEGIN
    SET @tableName = 'categories'
END
ELSE
BEGIN
   SET @tableName = 'employees'
END

declare @sql varchar(8000)
set @sql = 'SELECT * FROM ' + @tableName
exec(@sql)

-- only try and transfer records if some exist
IF (@@rowcount) > 0
BEGIN
     PRINT 'There are records in the table'
END
0
 
LVL 143

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 100 total points
ID: 16930206
use sp_executesql to get results back from dynamic sql:

DECLARE @type int
DECLARE @tableName varchar(200)
DECLARE @rowCount int

SET @type = 7

IF @type = 7
BEGIN
    SET @tableName = 'table1'
END
ELSE
BEGIN
   SET @tableName = 'table2'
END

declare @sql varchar(8000)
set @sql = 'SELECT @res = count(*) FROM ' + @tableName
exec sp_executesql @sql, N'@res int' , @rowcount OUTPUT

IF (@rowcount = 0)
...
0
 
LVL 50

Expert Comment

by:Lowfatspread
ID: 16930923
you shouldn't write procedures like this ...
this is a very poor style and requires dynamic sql to provide the result....
which can lead to all sorts of security and performance issues...

you need to re-evaluate your requirements...

what are you actually trying to achieve?
in what circumstance do you need the information?
  (dynamic sql can be ok in a System management sense...)


0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ready to get certified? Check out some courses that help you prepare for third-party exams.
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question