TSQL update 简单应用小总结

时间:2024-10-19 23:36:32

UPDATE 有两种基本的格式。一种是用静态数据来修改表,另一种是用其他表中的数据来修改表。下面是第一种格式:

 UPDATE #famousjaycees
SET jc = 'Jhony cash',
occupation = 'singer/songwrite',
becamefamous = 1955,
notes = 'began c'
WHERE jc = 'Jhony caeer'

第二种格式如下:

 IF NOT EXISTS
(SELECT *
FROM sys.sysobjects
WHERE [name] = 'semifamousjaycees')
CREATE TABLE semifamousjaycees
(
jc VARCHAR (15),
occupation VARCHAR (25),
becamefamous INT DEFAULT 0,
notes TEXT NULL
) UPDATE f
SET jc = s.jc,
occupations = s.occupations,
becamefamous = s.becamefamous,
notes = s.notes
FROM famousejaycees f
JOIN semifamousjaycee ON (f.becamesou = s.becamefouse)

UPDATE 的另外一种用途:使用update 检测约束。

如果使用 bulk insert 或者其他大批量的载入工具来对有insett 触发器的表进行追加数据,你们你会发现触发器不能触发。而且,即使bulk insert 不妨碍约束,也会是操作变的非常的慢。如果在载入数据时忽略约束,那么就快的多了。所以,比较的好的方法是,载入数据结束后,马上在对表一个假的update 操作。这个假的修改操作只是简单地将列值为其身的值。这样就会触发触发器约束进行检测。如果其中有包含错数数据的行,那么update失败.例如:

 IF NOT EXISTS
(SELECT *
FROM sys.sysobjects
WHERE [name] = 'famousejaycees')
CREATE TABLE famousejaycees
(
jc VARCHAR (15) CHECK (left (jc, 3) <> 'Joe'), -- establish a check constraint
occupation VARCHAR (25),
becamefamous INT DEFAULT 0,
notes TEXT NULL
)
go BULK INSERT famousejaycees
FROM 'C:\famous.bcp'
WITH (FIELDTERMINATOR = '|', ROWTERMINATOR = '\r\n') --check that the miscreant is in place
SELECT * FROM famousejaycees --now do the faux update update famousejaycees
set jc=jc, occupation = occupation, becamefamous = becamefamous, notes = notes

使用update 交换行列:

IF NOT EXISTS
(SELECT *
FROM sys.sysobjects
WHERE [name] = 'sample')
CREATE TABLE sample
(
k1 INT IDENTITY,
samp1 FLOAT DEFAULT (rand () * 1000),
samp2 FLOAT DEFAULT (rand () * 1000)
) SELECT * FROM sample; DECLARE @swap FLOAT UPDATE sample
SET @swap = samp1, samp1 = samp2, samp2 = @swap