具有多个更新语句的打印命令

时间:2017-03-30 13:20:18

标签: sql sql-server-2008 sql-update

我正在尝试运行多个更新,并在每个更新后打印一条消息,以便我可以跟踪任何错误。我遇到的问题是,如果第三次更新失败,它会抛出错误,我的消息都没有通过成功更新。如何让查询在每个更新语句后运行打印,而不是在每个更新语句之后放置'GO'? (我希望能够将包含的作品折叠为一个区域)

SET NOCOUNT ON
BEGIN TRANSACTION --CUSTOMERS

SELECT *INTO #T FROM CUST where cus_pk !=1
ALTER TABLE #T ADD NEW_PK INT NOT NULL IDENTITY(50955001,1000)

UPDATE P
SET P.CUS_FK= T.NEW_PK
FROM PRUDUCT P
JOIN #T T ON T.CUS_PK= P.CUS_FK
PRINT'UPDATED PRODUCT CUS_FK'

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK
PRINT'UPDATED ITEMS CUS_FK'

UPDATE A
SET A.CUS_FK= T.NEW_PK
FROM ACCT A
JOIN #T T ON T.CUS_PK= A.CUS_FK
PRINT'UPDATED ACCT_FK'

UPDATE S
SET S.CUS_FK= T.NEW_PK
FROM SOLD S
JOIN #T T ON T.CUS_PK= S.CUS_FK
PRINT'UPDATED SOLD CUS_FK'

UPDATE c
SET C.CUS_PK= T.NEW_PK
FROM CUST C
JOIN #T T ON T.CUS_PK= C.CUS_PK
PRINT'UPDATED CUST CUS_PK'

DROP TABLE #T
ALTER TABLE CUST NOCHECK CONSTRAINT FK_CUST_LOOKUP_C3
ALTER TABLE CUST NOCHECK CONSTRAINT FK_CUST_LOOKUP_C5

INSERT INTO CUST SELECT * FROM [DATABSE2].DBO.cust where cus_pk != 1

ALTER TABLE CUST CHECK CONSTRAINT FK_CUST_LOOKUP_C3
ALTER TABLE CUST CHECK CONSTRAINT FK_CUST_LOOKUP_C5
PRINT'NEW CUSTOMERS ADDED'
GO

1 个答案:

答案 0 :(得分:0)

是的,GO就是这样。此外,您应该在每个SQL语句结束后包括语句终止符;,如

UPDATE P
SET P.CUS_FK= T.NEW_PK
FROM PRUDUCT P
JOIN #T T ON T.CUS_PK= P.CUS_FK;
PRINT'UPDATED PRODUCT CUS_FK';

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK;
PRINT'UPDATED ITEMS CUS_FK';

同样,您可以考虑使用PRINT语句,而不是使用SELECT语句。

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK;
SELECT 'UPDATED ITEMS CUS_FK';