gpt4 book ai didi

sql - TSQL BINARY_CHECKSUM 作为默认值

转载 作者:行者123 更新时间:2023-12-04 17:09:41 26 4
gpt4 key购买 nike

表中有一列,应该存储列列表的校验和,但我想将其创建为该表的默认值:

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 作为该列的默认值吗?

最佳答案

基本上你不能。但是你可以用触发器做类似的事情。见下文

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

关于sql - TSQL BINARY_CHECKSUM 作为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com