October 10, 2006 at 12:50 pm
declare @townID varchar(25)
set @townID = '''00005'''
print @townID
if exists (select * from sysobjects where xtype= 'u' and name = @townID)
drop table @townID
why am i getting a syntax error.?
October 10, 2006 at 1:04 pm
You cannot reference a variable value as part of a DDL statement. In order to accomplish what you are attempting, you must use Dynamic SQL. Using your example,
declare @townID varchar(25),
@sql varchar(1000)
set @townID = '''00005'''
print @townID
if exists (select * from sysobjects where xtype= 'u' and name = @townID)
begin
set @sql = 'drop table ' + @townID
exec (@sql)
end
October 11, 2006 at 6:26 am
declare @townID varchar(25),
@sql varchar(1000)
set @townID = '''00003'''
if exists (select * from sysobjects where xtype= 'u' and name = @townID)
print 'exists'
else
print 'don''t exists'
its printing 'dont exists'. it should print exists as the table exists in the DB
what's wrong with it.?
October 11, 2006 at 6:49 am
It's the triple quotes in the variable assignment that are the most recent problem...
Try this...
declare @townID varchar(25),
@sql varchar(1000)
set @townID = '00003' --<<THIS IS WHERE THE PROBLEM WAS
if exists (select * from sysobjects where xtype= 'u' and name = @townID)
print 'exists'
else
print 'don''t exists'
Now, instead of messing around with System Tables, let's do it the right way (the dynamic SQL has been commented out for safety but YOU can uncomment it when you're ready)...
DECLARE @TownID VARCHAR(25)
DECLARE @SQL VARCHAR(8000)
SET @TownID = '00003'
IF OBJECT_ID(@TownID) IS NOT NULL
AND OBJECTPROPERTY(OBJECT_ID(@TownID),'IsTable') = 1
BEGIN
PRINT 'Exists'
SET @SQL = 'DROP TABLE '+@TownID
PRINT @SQL --Comment this line out when you uncomment the EXEC
-- EXEC @SQL --Commented out for safety
END
ELSE
BEGIN
PRINT 'NOT Exists'
END
--Jeff Moden
Change is inevitable... Change for the better is not.
October 11, 2006 at 7:15 am
Jeff Moden what is the problem with sysobjects
October 11, 2006 at 7:27 am
There's really no physical problem to keep you from using it... However, Microsoft and a bunch of folks on this forum have indicated that in order to guarantee that your code will work in the future (post service pack, new release, whatever), you need to stay away from sysobjects because Microsoft could change it at ANY time. Most equate calls to system tables at the same level as using undocumented sp/xp's that could also go away at the drop of a hat. The system functions make a nice clean way to get around that. You could also use the Information_Schema views but I just like the functions better... seems cleaner.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply