?
Solved

IF statement execution dependant on record count

Posted on 2006-06-18
10
Medium Priority
?
314 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
8 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 free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Suggested Courses

809 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