表中有一列,应该存储Checksum列的列,但我想将其创建为此表的默认值:
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
1,“2015-05-25”,1,1,1,“2015-11-11”, 46173
但遗憾的是,表“默认”表创建失败了。
可以查询:
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作为列的默认值?
答案 0 :(得分:3)
您可以将列创建为计算列。试试这个
CREATE TABLE tblVitalyTest
(id BIGINT IDENTITY(1,1),
startTime DATETIME,
value1 INT,
value2 INT,
value3 INT,
value4 DATETIME,
cksum AS BINARY_CHECKSUM(value1,value2, value3, value4 ))
GO
或者你可以改变现有的表格
ALTER TABLE tblVitalyTest
ADD cksum AS BINARY_CHECKSUM(value1, value2, value3, value4);
GO
此查询的结果(基于您的INSERT示例):
select id, cksum
from tblVitalyTest
将是:
id cksum
1 46173
2 46941
3 -44486
4 33885
5 -44487
答案 1 :(得分:3)
基本上你不能。但你可以用触发器做类似的事情。见下文
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