1

我有一个表可以对来自多个来源的选定文件进行编目。我想在新文件编目时记录一个文件是否是以前编目文件的副本。我在我的表中有一列(“primary_duplicate”)来记录每个条目为'P'(主)或'D'(重复)。我想为此列提供一个默认绑定,以检查新文件正在被记录时该文件的其他情况(即名称,长度,时间戳)如何使用Sql Server列的默认绑定的参数化函数

我已经创建了一个执行此检查的函数(请参阅下面的“GetPrimaryDuplicate”)。但我不知道如何绑定这个函数,它需要三个参数作为其默认绑定表的“primary_duplicate”列。

我想避免使用触发器。我目前有一个存储过程用于插入执行此检查的新记录。但是我想确保如果在此存储过程之外执行插入操作,标志设置正确。

如何使用插入的行中的值调用此函数?

USE [MyDatabase] 
GO 

SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE TABLE [dbo].[FileCatalog](
    [id] [uniqueidentifier] NOT NULL, 
    [catalog_timestamp] [datetime] NOT NULL, 
    [primary_duplicate] [nchar](1) NOT NULL, 
    [name] [nvarchar](255) NULL, 
    [length] [bigint] NULL, 
    [timestamp] [datetime] NULL 
) ON [PRIMARY] 

GO 

ALTER TABLE [dbo].[FileCatalog] ADD CONSTRAINT [DF_FileCatalog_id] DEFAULT (newid()) FOR [id] 
GO 

ALTER TABLE [dbo].[FileCatalog] ADD CONSTRAINT [DF_FileCatalog_catalog_timestamp] DEFAULT (getdate()) FOR [catalog_timestamp] 
GO 

ALTER TABLE [dbo].[FileCatalog] ADD CONSTRAINT [DF_FileCatalog_primary_duplicate] DEFAULT (N'GetPrimaryDuplicate(name, length, timestamp)') FOR [primary_duplicate] 
GO 


USE [MyDatabase] 
GO 

SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE FUNCTION [dbo].[GetPrimaryDuplicate] 
(
    @name nvarchar(255), 
    @length bigint, 
    @timestamp datetime 
) 
RETURNS nchar(1) 
AS 
BEGIN 

    DECLARE @c int 

    SELECT @c = COUNT(*) 
    FROM FileCatalog 
    WHERE [email protected] and [email protected] and [email protected] and primary_duplicate = 'P' 

    IF @c > 0 
     RETURN 'D' -- Duplicate 

    RETURN 'P' -- Primary 

END 

GO 
+0

我为穷人代码格式化道歉 - 不知道为什么有些代码没有被列入格式化 - 以及如何纠正它。 – 2010-03-27 06:01:40

回答

1

您应该改用触发器。触发器将收到插入行的副本。

2

约翰,这不是问题的答案,而且假定他应该使用触发器是非常冒失的。你不知道他想要做什么,或者他有什么理由想以默认价值来做。

如果这是不可能的,你可能会说“这不可能,所以你应该使用触发器”,这样他才能真正学到一些东西。我相信他知道你做什么触发和他们可以用于什么。

OP:对不起,但我正在寻找相同的信息。

2

好吧,我在发布这个问题后第一次问2.5年后,但:您是否考虑过使用primary_duplicate列的计算列,而不是使用默认绑定的常规列?

根据MSDN,DEFAULT定义中的“constant_expression”不能引用表中的另一列或其他表,视图或存储过程。

另一方面,计算列可以。

定义你的功能,因为这:

CREATE FUNCTION [dbo].[GetPrimaryDuplicate] 
(
    @id uniqueidentifier, 
    @catalog_timestamp datetime, 
    @name nvarchar(255), 
    @length bigint, 
    @timestamp datetime  
) 
RETURNS nchar(1) 
AS 
BEGIN 

IF EXISTS (
    SELECT 1 
    FROM FileCatalog 
    WHERE [email protected] and [email protected] and [email protected] 
     and catalog_timestamp < @catalog_timestamp 
) 
    RETURN 'D' -- Duplicate 

    RETURN 'P' -- Primary 

END 

然后执行以下ALTER TABLE语句:

GO 
ALTER TABLE [dbo].[FileCatalog] DROP COLUMN primary_duplicate 
ALTER TABLE [dbo].[FileCatalog] ADD primary_duplicate as dbo.GetPrimaryDuplicate(id, catalog_timestamp, name, length, timestamp)