简体   繁体   中英

t-SQL UPDATE table after adding columns to it with ADD TABLE

I have to add several columns to the table and then update them in SQL Server 2008. The table definition boils down to this:

CREATE TABLE tbl (id INT PRIMARY KEY, 
                  dvt NVARCHAR(32), 
                  dd NVARCHAR(32));
INSERT INTO tbl (id, dvt, dd) 
 VALUES(1, '1', NULL);
INSERT INTO tbl (id, dvt, dd) 
 VALUES(2, '', NULL);
INSERT INTO tbl (id, dvt, dd) 
 VALUES(3, '2,5', NULL);
INSERT INTO tbl (id, dvt, dd) 
 VALUES(4, '13, 34, 45, 5', NULL);
INSERT INTO tbl (id, dvt, dd) 
 VALUES(5, '-1, 8, 10', NULL);
INSERT INTO tbl (id, dvt, dd) 
 VALUES(6, '-2, -10', NULL);

How do I add data to the table in the same transaction that created the table?

Try something like

SET XACT_ABORT ON     
**--BEGIN TRANSACTION** 

ALTER TABLE tbl ADD d0 SMALLINT NULL 
ALTER TABLE tbl ADD d1 SMALLINT NULL 
ALTER TABLE tbl ADD d2 SMALLINT NULL 

GO

UPDATE tbl 
 SET 
 d0 = 1, 
 d1 = 2, 
 d2 = 3 

**--COMMIT TRANSACTION** 
SET XACT_ABORT OFF 

SELECT * FROm tbl

Without the transaction

The update statement must be enclosed in EXEC() block.

SET XACT_ABORT ON     
BEGIN TRANSACTION

IF 1=1 BEGIN  --used for simplicity to illustrate condition

ALTER TABLE tbl ADD d0 SMALLINT NULL 
ALTER TABLE tbl ADD d1 SMALLINT NULL 
ALTER TABLE tbl ADD d2 SMALLINT NULL 

EXEC('UPDATE tbl SET d0 = 1, d1 = 2, d2 = 3')

END

COMMIT TRANSACTION
SET XACT_ABORT OFF 

SELECT * FROm tbl

(This answer is actually ahmd0's answer, hence posting it as community wiki. However, his putting his answer in his question made it difficult for googlers like myself to idenitfy (and upvote) the answer we like.)

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