Solved

IF statement execution dependant on record count

Posted on 2006-06-18
10
297 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
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 

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 25 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 25 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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

I have a large data set and a SSIS package. How can I load this file in multi threading?
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

738 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