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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic if exists

Status
Not open for further replies.

vasah20

Programmer
Feb 16, 2001
559
US
is it possible to do a dynamic IF EXISTS statement?

something along the lines of

CREATE PROCEDURE sp_blah
(
@tblName NVARCHAR(100)
)
AS
IF EXISTS sp_executesql N'SELECT this FROM ' & @tblName
...

any ideas to do this would be greatly appreciated.

thanks
leo
 
Try this... Modify as needed for your data types.

CREATE PROCEDURE sp_blah
(
@tblName NVARCHAR(100)
)
AS

Declare @sql varchar(1024)

Set @sql='Select TOP 1 this From ' + @tblName

Create table #t (this varchar(40))

Insert #t
exec(@sql)

if exists (Select * From #t)
Print 'good'
Else
Print 'bad'

drop table #t Terry

The reason why worry kills more people than work is that more people worry than work. - Robert Frost
 
Hi leo,

If you want to check the IF Exists dynamically, you can use the following code also. The difference is you don't have to create/drop a temporary table.
------------------------------
CREATE PROCEDURE sp_blah
(
@tblName NVARCHAR(100)
)
AS
declare @sql varchar(1024)
Set @sql='Select this From ' + @tblName
exec(@sql)
IF @@rowcount>0
Print 'EXIST'
ELSE
Print 'Not Exist'
------------------------------

May this help you!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top