Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use If EXIST() in a stored Proc

Status
Not open for further replies.

smithsf22

Programmer
Mar 13, 2006
5
CA
Hello,
I am trying to make a stored proc that will tell me if there are any rows in a table. The table name is a variable that I get at the start of the proc it is not sent in. What I am looking for in the table is sent into the stored proc.

here is what i have so far but it does not work, i can not save it. It does not seem to allow me to use the if exists with variables. I have tired to get this to run ever which way, without the + with the +' and just plane old +

if exists (SELECT * FROM + @TableName + WHERE + @ColumnName + = + @SearchStr2)

print 'got here ' +@TableName + ' '+ @ColumnName

END

Thanks for any help
 
You can probably just issue a straight SELECT (in an EXEC function) and test @@rowcount.

Try this:
USE Northwind
declare @tablename sysname
declare @columnname sysname
declare @searchstr2 varchar(128)
declare @sql varchar(512)

set @tablename = 'Categories'
set @columnname = 'CategoryName'
set @searchstr2 = 'condiments' --replace with 'cow dung' to see zero rows

set @sql = 'SELECT * FROM '+@tablename+' WHERE '+@columnname +' = '''+@searchstr2+''''
exec (@sql)
print @@ROWCOUNT

Phil Hegedusich
Senior Programmer/Analyst
IIMAK
-----------
I'll have the roast duck with the mango salsa.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top