简体   繁体   中英

Using Update, Delete and Insert Statements in a single Stored Procedure on SQL Server 2008 R2

I have a scenario that requires me to firstly set a range of column values in a table to Null, then I add the logic to re-calculate the new NULL values with an Update statement following the previous Update statement. Lastly I run my final comparison script (within a cursor) which inserts the new values into a table.

Do I need to use the GO command between each major command?

Example:

Drop Table1

Update Table2
Set Col1=NULL,Col2=NULL

Insert into Table3 (Col1,Col2)

Is using a GO between each statement a requirement as sometimes this works but lately it's been giving me issues?

Thanks,

As mentioned above, GO is not an SQL syntax, but SSMS separator.

If you really need to perform all those actions in the single SP, you can use a dynamic SQL. The're two abilities to execute dynamic SQL in the SQL server" sp_executesql and execute (command) .

Additional information according to the dynamic SQL can be found here: http://www.sommarskog.se/dynamic_sql.html or here: http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure

In this case your script will be like following:

create proc myProc
as
declare @sql nvarchar(max);

set @sql = N'Drop Table1';
exec sp_executesql @sql;

set @sql = N'Update Table2
Set Col1=NULL,Col2=NULL';
exec sp_executesql @sql;

set @sql = N'Insert into Table3 (Col1,Col2)';
exec sp_executesql @sql;
go

But need to check if you really need to perform the above operations in the mentioned above manner...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM