Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
spinningtop
Starting Member
29 Posts |
Posted - 2012-05-08 : 06:32:14
|
Hi If I wanted to check if a tables existed before dropping it so it doesn't kick up a table does not exist error in the program I would use the code below. However my problem is that the schema name is not [dbo] but has a variable name created by the user at runtime. I have been trying to change the code below to dynamic sql so I can add the variable $schemaname instead of [dbo] below but I can't get it to work. Any help would be appreciated thanks USE [database]GOIF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[table]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)DROP TABLE [dbo].[table] |
|
Transact Charlie
Master Smack Fu Yak Hacker
3451 Posts |
Posted - 2012-05-08 : 06:43:55
|
you could do something like this:USE [Tempdb]GOCREATE SCHEMA fooGOCREATE TABLE foo.bar ([woo] BIT)INSERT foo.bar VALUES (1)GOIF OBJECT_ID('foo.bar') IS NOT NULL SELECT 'Foo.Bar Exists'ELSE SELECT 'Foo.Bar DOES NOT Exist'GODECLARE @schemaName SYSNAME = 'foo'DECLARE @tableName SYSNAME = 'bar'DECLARE @QualifiedName SYSNAME = QUOTENAME(@schemaName) + '.' + QUOTENAME(@tableName)DECLARE @sql NVARCHAR(MAX)IF OBJECT_ID(@QualifiedName) IS NOT NULLBEGIN SET @sql = 'DROP TABLE ' + @QualifiedName PRINT @sql EXEC sp_executeSql @sqlENDIF OBJECT_ID('foo.bar') IS NOT NULL SELECT 'Foo.Bar Exists'ELSE SELECT 'Foo.Bar DOES NOT Exist'GO-- CleanupDROP SCHEMA fooGO Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION |
 |
|
Transact Charlie
Master Smack Fu Yak Hacker
3451 Posts |
Posted - 2012-05-08 : 06:45:04
|
Note I wrapped all input using QUOTENAME()This should give good protection from sql injection. However it won't stop anyone from dropping the wrong table if they get the parameter names wrong.Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION |
 |
|
spinningtop
Starting Member
29 Posts |
Posted - 2012-05-08 : 11:49:07
|
Thanks very much. This works very well |
 |
|
|
|
|