sql - 在 SQL Server 2005 中保留计算的日期时间列

标签 sql sql-server sql-server-2005

我的表中有一个 XML 列;我想将该 XML 中的某个值“提升”为计算列并为其建立索引以加快搜索速度。我有一个函数,它接受 XML 信息并输出感兴趣的元素,如下所示:

CREATE FUNCTION [dbo].[fComputeValue] (@data XML)
RETURNS datetime
WITH SCHEMABINDING
AS
BEGIN
  RETURN @data.value('(/Metadata/Value[@Key="StartDate"])[1]', 'datetime')
END 

但是,当我尝试创建计算列时:

ALTER TABLE dbo.CustomMetadataTable ADD [StartDate] AS ([dbo].[fComputeValue]([CustomMetadataColumn])) PERSISTED

我收到以下错误:

Msg 4936, Level 16, State 1, Line 2 Computed column 'StartDate' in table 'CustomMetadataTable' cannot be persisted because the column is non-deterministic.

如果我:

  • 使用 varchar、int、double(即日期时间以外的值)
  • 删除 PERSISTED 关键字(但随后我无法在该列上创建索引)

我还应该提到日期时间值采用 XSD 日期时间格式。 有任何想法吗?谢谢。

最佳答案

关于:

CREATE FUNCTION [dbo].[fComputeValue] (@data XML)
RETURNS varchar(50)
WITH SCHEMABINDING
AS
BEGIN
  RETURN @data.value('(/Metadata/Value[@Key="StartDate"])[1]', 'varchar(50)')
END

和:

ALTER TABLE dbo.CustomMetadataTable ADD [StartDate] AS (convert(datetime,([dbo].[fComputeValue]([CustomMetadataColumn]), 127)) PERSISTED

或者:

return convert(datetime, @data.value('(/Metadata/Value[@Key="StartDate"])[1]', 'varchar(50)'), 127)

来自在线书籍:

CONVERT is Deterministic unless one of these conditions exists:

Source type is sql_variant.

Target type is sql_variant and its source type is nondeterministic.

Source or target type is datetime or smalldatetime, the other source or target type is a character string, and a nondeterministic style is specified. To be deterministic, the style parameter must be a constant. Additionally, styles less than or equal to 100 are nondeterministic, except for styles 20 and 21. Styles greater than 100 are deterministic, except for styles 106, 107, 109 and 113.

如果您使用 CONVERT 和样式 127 可能会有所帮助

关于sql - 在 SQL Server 2005 中保留计算的日期时间列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/246666/

相关文章:

mysql - sql 一个字段有多个键

c# - 使用 asp.NET C# 将数据从谷歌地图插入数据库

mysql - sql填充新创建的链接表

sql - 如何授予用户对 SQL Server 中数据库的读取访问权限?

mysql - 如果子查询连接列(如果存在),则显示行

sql-server - 如何防止MS SQL数据库中出现重复项?

sql-server - SQL Server (2005) - "Deleted On"DATETIME 和索引

sql-server-2005 - 识别SQL Server 2005中最常用的存储过程变体的最快方法

sql-server-2005 - 触发器中插入/更新行的标识

c# - 尝试从存储过程中读取多个实体结果集时出现问题