SQL Incorrect Syntax Near 'GO' - sql

I am getting the error in my sproc and I cannot figure out why. I have looked at other, almost identical questions like this Here and the answers aren't doing the trick for me. the syntax error is at the 'Go' right after the database creation.
USE [DATABASENAME]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Sproc]
#Id int
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name =
N'Name')
create database Name;
GO
CREATE TABLE [Name].[dbo].[Account](
[Id] [int] IDENTITY(1,1) NOT NULL,
[AccountId] [int] NOT NULL
);

GO is not allowed in stored procedures. It separates batches and a procedure itself is one batch which cannot be separated.
You could use one procedure to create the database, then a second procedure to create the table.
Edit
Actually you could do it in one procedure:
CREATE PROCEDURE [dbo].[Sproc]
AS
BEGIN
EXEC ('USE [Master]; CREATE DATABASE [name]')
EXEC ('USE [Name]; CREATE TABLE [name].dbo.[Account] (id int)')
END

Related

TRY...CATCH doesn't seem to work

I have the following piece of code that's just to make sure that the temporary table doesn't exist. If the table exist I want to truncate it.
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
) --I create this just to test my try-catch
BEGIN TRY
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
)
END TRY
BEGIN CATCH
PRINT N'#LookupLinks already existed and was truncated.';
TRUNCATE TABLE #LookupLinks
END CATCH
What I want this to do:
The temp-table is created
Attempt to create it again
error sends us into the catch
table is truncated and everything continues as normal
What happens:
ERROR: There is already an object named '#LookupLinks' in the database.
What am I doing wrong here?
This is because SQL Server parses and validates the whole batch. So when parsing the second CREATE TABLE statement, it errors out saying:
There is already an object named '#LookupLinks' in the database.
See this example:
IF 1 = 1 BEGIN
CREATE TABLE #temp(col INT)
END
ELSE BEGIN
CREATE TABLE #temp(col INT)
END
It produces an error saying:
There is already an object named '#temp' in the database.
The workaround is to use Dynamic SQL.
-- CREATE the table for testing
IF OBJECT_ID('tempdb..#LookupLinks') IS NOT NULL
DROP TABLE #LookupLinks
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
)
-- Final query
IF OBJECT_ID('tempdb..#LookupLinks') IS NOT NULL BEGIN
TRUNCATE TABLE #LookupLinks
PRINT N'#LookupLinks already existed and was truncated.'
END
ELSE BEGIN
DECLARE #sql NVARCHAR(MAX) = ''
SELECT #sql = '
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
)'
EXEC sp_executesql #sql
PRINT N'#LookupLinks was created.'
END
If you do not have the first CREATE TABLE statement,your query will work just fine. Or if you put a GO before the BEGIN TRY.
IF OBJECT_ID('tempdb..#LookupLinks') IS NOT NULL
DROP TABLE #LookupLinks -- DROP FIRST
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
) --I create this just to test my try-catch
GO
BEGIN TRY
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
)
END TRY
BEGIN CATCH
PRINT N'#LookupLinks already existed and was truncated.';
TRUNCATE TABLE #LookupLinks
END CATCH
Still, it's because SQL server parses and validates the whole batch. The GO statement will put the statements into their own batches, thus the error is now not happening.
Even CeOnSql's answer will work fine.
I think what you really want to achieve is this:
IF OBJECT_ID('tempdb..#LookupLinks') IS NOT NULL --Table already exists
BEGIN
TRUNCATE TABLE #LookupLinks
PRINT N'#LookupLinks already existed and was truncated.';
END
ELSE
BEGIN
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
)
END
TRY CATCH is for run time error. What you are getting is a compile time error. Add a PRINT 1 before your statement and you'll see that nothing is getting executed.
print 1
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
);
BEGIN TRY
CREATE TABLE #LookupLinks(
[SyncID] uniqueidentifier,
[Name] nvarchar(50),
[SQLTable] nvarchar(50)
);
END TRY
BEGIN CATCH
PRINT N'#LookupLinks already existed and was truncated.';
TRUNCATE TABLE #LookupLinks
END CATCH

Deletion\Creation of Temp tables in SQL Server 2008

I have SQL code like this
IF Object_id('tempdb..#empDate) IS NOT NULL
DROP TABLE #empDate
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
After the above code some more lines of SQL follow and then it is repeated.
I get the following error.
Msg 2714, Level 16, State 1, Line 589
There is already an object named '#empDate' in the database.
I replaced the
IF Object_id('tempdb..#empDate) IS NOT NULL
with
IF Object_id('tempdb..#empDate%) IS NOT NULL
As it is written on the forums that SQL Server appends number to the subsequent temp table(s).
Source:
Check if a temporary table exists and delete if it exists before creating a temporary table
http://blog.sqlauthority.com/2009/05/17/sql-server-how-to-drop-temp-table-check-existence-of-temp-table/
http://blog.sqlauthority.com/2009/03/29/sql-server-fix-error-msg-2714-level-16-state-6-there-is-already-an-object-named-temp-in-the-database/
I am using Microsoft SQL Server 2008 on Windows 7 Enterprise.
I am not able to understand the cause of the error.
Please help.
Sample One
This will fail......
Executing the same code again, will throw the error you are getting now
IF Object_id('tempdb..#empDate') IS NOT NULL
BEGIN
DROP TABLE #empDate
END
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
IF Object_id('tempdb..#empDate') IS NOT NULL
BEGIN
DROP TABLE #empDate
END
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
Sample Two (Fixed)
IF Object_id('tempdb..#empDate') IS NOT NULL
BEGIN
DROP TABLE #empDate
END
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
GO --<-- Adding this Batch Separator will eliminate the Error
IF Object_id('tempdb..#empDate') IS NOT NULL
BEGIN
DROP TABLE #empDate
END
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
Test
If you try Executing the following Statements in ONE BATCH they will fail even though there isnt any table at all with the name #empDate, it will not even execute the very 1st Create table Statement. and will throw an error.
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
DROP TABLE #empDate
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
But if you separate all the statement in separate batches they will be executed successfully something like this..
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
GO
DROP TABLE #empDate
GO
CREATE TABLE #empDate
(
[empID] INT,
[AddLoc] VARCHAR(1000)
)
GO
I would just drop your table without any pre-checks.
Then write/run the script clean.
Once done using the temp table, drop it at the end of your script.
So run this unconditionally
DROP TABLE #empDate
Then write/run your script and make sure you have this line at the end of your script.
pass database name with object_id
example :
DECLARE #db_id int;
DECLARE #object_id int;
SET #db_id = DB_ID(N'AdventureWorks2012');
SET #object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF #db_id IS NULL
BEGIN;
PRINT N'Invalid database';
END;
ELSE IF #object_id IS NULL
BEGIN;
PRINT N'Invalid object';
END;
ELSE
BEGIN;
SELECT * FROM sys.dm_db_index_operational_stats(#db_id, #object_id, NULL, NULL);
END;
GO

unable to drop and create database in sql server

I'm working with SQL Server 2008 and I can't seem to do drop and create a database.
I've tried a few different ways but I always end up failing to drop or trying to "use" before it seems to be created.
My current attempt looks like this.
use master;
GO
IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'test')
BEGIN
DROP DATABASE [test];
END
GO
CREATE DATABASE [test];
GO
use [test];
GO
The GO were suggested on a MS forum as a way to stop some issues that occur when selecting databases.
With this I currently get the output (with a ore existing database of the same name) of:
Msg 3702, Level 16, State 4, Line 3
Cannot drop database "test" because it is currently in use.
Msg 1801, Level 16, State 3, Line 1
Database 'test' already exists. Choose a different database name.
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'staff_type' in the database.
With the last 2 lines repeated for every table in my database.
We usually get this error If You've opened any query window with connection to this database, so make sure you close all your opened query windows connected to db which you're trying to drop.
Don't use the database which you're trying to drop. use master to drop any user database that is a good practice.
Make sure No other process is attach to the database you're trying to drop.
EXEC sp_who2
--Run kill spid for each process that is using the database to be dropped.
kill <<processid>> -- Kill 57
Use EXEC sp_who2 and check the DBName column, your database name should not appear in the list, if it appears kill the process using kill <<processid>> then try to drop.
Try this code.
use master
GO
IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'test')
DROP DATABASE [test]
GO
CREATE DATABASE [test]
GO
use [test]
GO
Right-click on the database and select "Delete" (or left-click it and press the 'del' key).
When the 'Delete Object' dialog appears, make sure to checked "Close existing connections" (see below, it's unchecked by default).
Press "OK".
try this:
use master;
GO
ALTER DATABASE test SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
.....
This will rollback any transaction which is running on that database and brings SQL Server database in a single user mode.
ALTER DATABASE test1 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE test1 SET OFFLINE;
DROP DATABASE test1
Try this inside stored procedure
This will give you all the current connections:
select spid, hostname, [program_name], open_tran, hostprocess, cmd
from master.dbo.sysprocesses
where dbid = db_id('your_database_name')
Then you could use a t-sql cursor to execute kill #spid, where the value for #spid is from the previous query.
If you are getting the above error while using Master. then you need to close SQL Server Management Studio completely and again open it and connect to it and run your above query.....
Hope,it'll works.....
If you're running into this after having programmatically interacted with the database via ADO.NET and SqlConnection, and you're sure you've closed each of your connections after use and there's really nobody else in there, you might be getting tripped up by connection pooling. Try this C# code to clear the pool prior to connecting to master or another database to issue the DROP DATABASE command on your database:
SqlConnection.ClearPool(yourSqlConnectionObject);
You need to close all the query window using this database also you might need to restart the SQL Server completely. This might solve your problem.
If you have SQL files open that have previously queried the DB you are trying to drop, these will prevent drop. As mention above. Closing these resolved issue for me
Along with mr_eclair's answer above, I would like to add:
All Query window must be closed where the currect db is selected.
Another option is make the db in single user mode.>> it will kill all the other users processes
set OFFLINE WITH ROLLBACK IMMEDIATE. it will make the db in offline mode and bring it back
use sp_who2 to know the users using the current db. and killthe required spids
I faced this type of problem when working with Sql Server Management Studio. After many days of googling and experiments, i finally found an issue.
NB: You ought to firstly create a drop and create table script for this table, if not you will not have your table
1-First create only yours tables with theirs coresponding foreign keys.
2-Create a visual diagram with these table (Sql express-Databases-Databasename-DataBase Diagram-Right click on it and select new database diagram)
3-Add the required datatables on diagram and create the relation between these datatables with corresponding foreign keys added during the creation of tables
4-Then saved your Database
In the case that you have forget to add a given field in a datatable, you can easily drop and create your datatables, to do this, follow these steps:
1-Open the Database diagram of the corresponding database
2-delete all the relationships which exist between the old table to which you want to add some field and others tables
3-then delete the corresponding table from diagram(right click on the table , then select delete table from the datatable)
4-Save the diagram (Ctrl +S)
5-go to the table that you want to drop and create
6-Right click on the table and select( Script table as then select drop and create then go to new Query editor windows), this will script your table in new table, at this time you can modify it to your need, exemple with and old and new same table
Old table
USE [DatabaseName]
GO
/****** Object: Table [dbo].[Administrateur] Script Date: 10/11/2016 2:06:04 PM ******/
DROP TABLE [dbo].[Administrateur]
GO
/****** Object: Table [dbo].[Administrateur] Script Date: 10/11/2016 2:06:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Administrateur](
[AdministrateurID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Surname] [nvarchar](max) NULL,
[Phone] [nvarchar](max) NOT NULL,
[Username] [nvarchar](max) NOT NULL,
[Password] [nvarchar](max) NOT NULL,
[Sexe] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Administrateur] PRIMARY KEY CLUSTERED
(
[AdministrateurID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Now the NEW SAME TABLE WITH 3 NEW FIELDS(Email, Image and Salt)
USE [DatabaseName]
GO
/****** Object: Table [dbo].[Administrateur] Script Date: 10/11/2016 2:06:04 PM ******/
DROP TABLE [dbo].[Administrateur]
GO
/****** Object: Table [dbo].[Administrateur] Script Date: 10/11/2016 2:06:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Administrateur](
[AdministrateurID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Surname] [nvarchar](max) NULL,
[Phone] [nvarchar](max) NOT NULL,
[Email] [nvarchar](max) NOT NULL,
[Username] [nvarchar](max) NOT NULL,
[Password] [nvarchar](max) NOT NULL,
[Image] [nvarchar](max) NOT NULL,
[Sexe] [nvarchar](max) NOT NULL,
[Salt] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Administrateur] PRIMARY KEY CLUSTERED
(
[AdministrateurID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Then in the page of the modified Datatable, Press Execute. It will not execute for the first time and will write some errors encountered, but don't care and just press Execute in second time. At this time, it will execute and write the success message at the bottom of the document.Then select the database and click on Refresh (or press F5), he will update your Database's tables in some computer or you will need to restart the program before seing the updates in others computers(I don't know why, so don't ask me to explain).
Go back now to the diagram and dd the updated table and then connect these(this) table(s) to the tables which has any relation with it.
Hope that this will save the time of someones.
I don
I know I´m late to the game. But here is how I do this in one step. This was happening so often I did´t want to do this in many steps so I combined it to one single step.
DECLARE #databaseName VARCHAR(30);
DECLARE #resource_type_to_kill VARCHAR(30);
DECLARE #processIdToKill INT;
SET #databaseName = 'yourDatabaseName'
SET #resource_type_to_kill = 'DATABASE'
DECLARE #TempSession TABLE
(
ProcessIdToKill INT,
DatabaseName VARCHAR(100),
Request_Mode VARCHAR(100),
HostName VARCHAR(100),
LoginTime VARCHAR(100),
LoginName VARCHAR(100),
Status VARCHAR(100),
Reads VARCHAR(100),
Writes VARCHAR(100)
);
INSERT #TempSession
SELECT DISTINCT
session_id,
name,
request_mode,
host_name,
login_time,
login_name,
status,
reads,
writes
FROM sys.dm_exec_sessions
LEFT OUTER JOIN sys.dm_tran_locks ON sys.dm_exec_sessions.session_id = sys.dm_tran_locks.request_session_id
INNER JOIN sys.databases ON sys.dm_tran_locks.resource_database_id = sys.databases.database_id
WHERE resource_type = #resource_type_to_kill
AND name = #databaseName
ORDER BY name
--SELECT * FROM #TempSession --Debugging
SELECT #processIdToKill = ProcessIdToKill FROM #TempSession
--SELECT #processIdToKill --Debugging
--Run kill for the process that is using the database to be dropped.
DECLARE #SQL nvarchar(1000)
SET #SQL = 'KILL ' + CAST(#processIdToKill as varchar(4))
PRINT 'Killing the process'
EXEC (#SQL)
--And then drop the database
DECLARE #DropSQL nvarchar(1000)
SET #DropSQL = 'DROP DATABASE ' + #databaseName
PRINT 'Dropping the database'
EXEC (#DropSQL)
If there are many processes that are using the database you´ll just have to run this multiple times.
Totally random thought here. But if you have a SQL DB project open in Visual Studio, its open-ness will occupy processes even if you aren't taking any actions or have open query windows in SSMS.
This was the issue in my case. Closing Visual Studio completely, allowed me to drop the database with no issue.
For linux try restarting mssql.server
sudo systctl mssql-server.service
then
DROP Databse "DatabseName"

A stored proc to copy table data including any default value or binding data via a SQL script running within SQL Server

I would like to be able to copy a table and it's data and also still have any default value or binding (as it is labelled within SQL Server Management console) constraints copied over.
The script below is a testing script to demonstrate the idea. The last line I assume needs to be replaced with a call to a custom stored proc?
Note: The source table (aSourceTbl) schema varies and can change over time.
--TEST SETUP
--Delete the prev tables so test script can be replayed
IF OBJECT_ID('aSourceTbl', 'U') IS NOT NULL
DROP TABLE aSourceTbl;
IF OBJECT_ID('aSourceCopyTbl', 'U') IS NOT NULL
DROP TABLE aSourceCopyTbl;
--Simple table to demonstrate table copying does not carry over the table constraits
CREATE TABLE [dbo].[aSourceTbl](
[aValue] [int] NOT NULL,
[DELETED] [int] NOT NULL
) ON [PRIMARY]
--Add some dummy data
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (1,2);
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (3,4);
--Add constraints of default values of 0 in this case
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_aValue] DEFAULT ((0)) FOR [aValue]
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_DELETED] DEFAULT ((0)) FOR [DELETED]
--Actual Required SQL script from here down
--The line below works nicely but does not copy the 2 constraints from the lines above into the new table.
--TODO QUESTION: Replace line below with the same functionaility + the constraints are also copied into new table
Select * INTO aSourceCopyTbl FROM aSourceTbl
Could you please help me by suggesting a suitable stored proc that can replace the last line in above SQL snippet? Any help greatly appreciated :)
References:
Similar SO Question however focuses on PK constraints. I am only interested in default value constraints in this case.
You can execute this code after the last row which will replicate the defauld constraints to the new table (replace the variables with your table names).
declare #table_name sysname, #new_table sysname, #cmd varchar(max)
select #table_name = 'SOURCE_TABLE', #cmd = '', #new_table = 'TEST_TABLE'
select #cmd = #cmd+'ALTER TABLE '+#new_table+' ADD CONSTRAINT [DF_' +#new_table+'_'+a.name+'] DEFAULT '+b.definition+' FOR['+a.name+'];
'
from sys.columns a
join sys.default_constraints b on a.object_id = b.parent_object_id and a.column_id = b.parent_column_id
where a.object_id = object_id(#table_name)
print #cmd
exec (#cmd)

Mirroring Table Modifications

I have a set of tables that are used to track bills. These tables are loaded from an SSIS process that runs weekly.
I am in the process of creating a second set of tables to track adjustments to the bills that are made via the web. Some of our clients hand key their bills and all of those entries need to be backed up on a more regular schedule (the SSIS fed data can always be imported again so it isn't backed up).
Is there a best practice for this type of behavior? I'm looking at implementing a DDL trigger that will parse the ALTER TABLE call and change the table being called. This is somewhat painful, and I'm curious if there is a better way.
I personally would have the SSIS-fed tables in one database (set to simple recovery mode) and the other tables in a separate database on the same server which is set to full recovery mode,. Then I would set up backups on the second datbase on a regular schedule. A typical backup schedule would be full backup once a week, differntials nightly and transaction backups every 15-30 minutes depending on how much data is being input.) Be sure to periodically test recovering the backups, learning how to do that when the customer is screaming becasue the datbase is down isn;t a good thing.
I ended up using a DDL trigger to make a copy of changes from one table to the other. The only problem is that if a table or column name contains part of a reserved word - ARCH for VARCHAR - it will cause problems with the modification script.
Thanks, once again, to Brent Ozar for error checking my thoughts before I blogged them.
-- Create pvt and pvtWeb as test tables
CREATE TABLE [dbo].[pvt](
[VendorID] [int] NULL,
[Emp1] [int] NULL,
[Emp2] [int] NULL,
[Emp3] [int] NULL,
[Emp4] [int] NULL,
[Emp5] [int] NULL
) ON [PRIMARY];
GO
CREATE TABLE [dbo].[pvtWeb](
[VendorID] [int] NULL,
[Emp1] [int] NULL,
[Emp2] [int] NULL,
[Emp3] [int] NULL,
[Emp4] [int] NULL,
[Emp5] [int] NULL
) ON [PRIMARY];
GO
IF EXISTS(SELECT * FROM sys.triggers WHERE name = ‘ddl_trigger_pvt_alter’)
DROP TRIGGER ddl_trigger_pvt_alter ON DATABASE;
GO
-- Create a trigger that will trap ALTER TABLE events
CREATE TRIGGER ddl_trigger_pvt_alter
ON DATABASE
FOR ALTER_TABLE
AS
DECLARE #data XML;
DECLARE #tableName NVARCHAR(255);
DECLARE #newTableName NVARCHAR(255);
DECLARE #sql NVARCHAR(MAX);
SET #sql = ”;
-- Store the event in an XML variable
SET #data = EVENTDATA();
-- Get the name of the table that is being modified
SELECT #tableName = #data.value(‘(/EVENT_INSTANCE/ObjectName)[1]‘, ‘NVARCHAR(255)’);
-- Get the actual SQL that was executed
SELECT #sql = #data.value(‘(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]‘, ‘NVARCHAR(MAX)’);
-- Figure out the name of the new table
SET #newTableName = #tableName + ‘Web’;
-- Replace the original table name with the new table name
-- str_replace is from Robyn Page and Phil Factor’s delighful post on
-- string arrays in SQL. The other posts on string functions are indispensible
-- to handling string input
--
-- http://www.simple-talk.com/sql/t-sql-programming/tsql-string-array-workbench/
-- http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-1/
--http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-2/
SET #sql = dbo.str_replace(#tableName, #newTableName, #sql);
-- Debug the SQL if needed.
--PRINT #sql;
IF OBJECT_ID(#newTableName, N’U’) IS NOT NULL
BEGIN
BEGIN TRY
-- Now that the table name has been changed, execute the new SQL
EXEC sp_executesql #sql;
END TRY
BEGIN CATCH
-- Rollback any existing transactions and report the full nasty
-- error back to the user.
IF ##TRANCOUNT > 0
ROLLBACK TRANSACTION;
DECLARE
#ERROR_SEVERITY INT,
#ERROR_STATE INT,
#ERROR_NUMBER INT,
#ERROR_LINE INT,
#ERROR_MESSAGE NVARCHAR(4000);
SELECT
#ERROR_SEVERITY = ERROR_SEVERITY(),
#ERROR_STATE = ERROR_STATE(),
#ERROR_NUMBER = ERROR_NUMBER(),
#ERROR_LINE = ERROR_LINE(),
#ERROR_MESSAGE = ERROR_MESSAGE();
RAISERROR(‘Msg %d, Line %d, :%s’,
#ERROR_SEVERITY,
#ERROR_STATE,
#ERROR_NUMBER,
#ERROR_LINE,
#ERROR_MESSAGE);
END CATCH
END
GO
ALTER TABLE pvt
ADD test INT NULL;
GO
EXEC sp_help pvt;
GO
ALTER TABLE pvt
DROP COLUMN test;
GO
EXEC sp_help pvt;
GO