Solved

IF statement execution dependant on record count

Posted on 2006-06-18
10
260 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
10 Comments
 
LVL 4

Expert Comment

by:indu_mk
Comment Utility
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
Comment Utility
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
Comment Utility
sorry for the typo, its exec not exes
0
 

Author Comment

by:ian_r
Comment Utility
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
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 33

Expert Comment

by:hongjun
Comment Utility
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
Comment Utility
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 142

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 25 total points
Comment Utility
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
Comment Utility
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

In this article—a derivative of my DaytaBase.org blog post (http://daytabase.org/2011/06/18/what-week-is-it/)—I will explore a few different perspectives on which week today's date falls within using Microsoft SQL Server. First, to frame this stu…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

744 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now