表中有一个列,它应该存储列列表的校验和,但我想将其创建为该表的默认值:
There is a column in a table, which should store Checksum for list of columns, but I'd like to create it as a default value for this table:
CREATE TABLE tblVitalyTest (id BIGINT IDENTITY(1,1), startTime DATETIME, value1 INT, value2 INT, value3 INT, value4 DATETIME, BinCheckSum BIGINT)
GO
ALTER TABLE tblVitalyTest ADD DEFAULT (BINARY_CHECKSUM(value1, value2, value3, value4)) FOR [BinCheckSum]
GO
所以,应该这样使用:
INSERT INTO tblVitalyTest (startTime,value1,value2,value3,value4) VALUES ('2015-05-25',1,1,1,'2015-11-11')
结果应该是这样的:
id、startTime、value1、value2、value3、value4、BinCheckSum
id, startTime, value1, value2, value3, value4, BinCheckSum
1, "2015-05-25", 1, 1, 1, "2015-11-11", 46173
1, "2015-05-25", 1, 1, 1, "2015-11-11", 46173
但不幸的是,表默认"表创建失败.
But table "default" table creation fails unfortunately.
有一个查询可以玩:
DECLARE @a TABLE (id BIGINT IDENTITY(1,1), startTime DATETIME, value1 INT, value2 INT, value3 INT, value4 DATETIME)
INSERT INTO @a (startTime,value1,value2,value3,value4)
VALUES ('2015-05-25 08:00',1,1,1,'2015-11-11'),('2015-05-25 09:00',1,2,1,'2015-11-11')
,('2015-05-25 10:00',null,null,null,'2015-11-11'),('2015-05-25 11:00',2,1,1,'2015-11-11'),('2015-05-25 11:00',null,null,null,'2015-11-12')
SELECT a.*,BINARY_CHECKSUM(a.value1,a.value2,a.value3,a.value4) [BinCheckSum]
FROM @a a
请告诉我有没有办法创建一个 Binary_Checksum 作为列的默认值?
Please let me know is there any way to create a Binary_Checksum as a default value for the column?
基本上你不能.但是你可以用触发器做类似的事情.见下文
Basically you can't. But you can do something similar with a trigger. See below
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER dbo.tblVitalyTestUpdateInsertTrigger ON dbo.tblVitalyTest
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE
vt
SET
vt.BinCheckSum = BINARY_CHECKSUM(vt.value1, vt.value2, vt.value3,
vt.value4)
FROM
dbo.tblVitalyTest vt
INNER JOIN INSERTED i
ON vt.id = i.id
END
GO
这篇关于TSQL BINARY_CHECKSUM 作为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!