1
create table Linq_TB
{
   url_id int NOTNULL,
   Pg_Name nvarchar(50) NOTNULL,
   URL nvarchar(50) NUTNULL,

   CONSTRAINT Linq_id PRIMARY KEY (url_id,DBCC Checkident(Linq_TB,RESEED,0) case url_id not in(select URL_Id from URL_TB ))
}

I want to make a table which it's primary key is Linq_id and gets it's value from both the url_id and identity with start from 1 and increments 1 by 1. url_id is a foreign key. For example if url_id is 1, linq_id's will be 11, 12, 13,... and I also want to reset linq_id identity when the url_id changes.

What should the query be? The query above doesn't work, why?

Thanks in advance

4

2 回答 2

0

好吧,约束包含条件而不是要执行的代码。您应该考虑为您的任务使用存储过程以及分配 ID 的本地方法。

但是,将主键“漂亮”或格式化并不是一种常见的做法,因为没有真正的好处(可能出于调试目的除外)。

我不建议在您的 url_ID 更改时执行 DBCC。这对性能有很大的负面影响。

你为什么不把身份证原样留下呢?

于 2012-12-29T11:47:05.887 回答
0

您可以使用下表和触发器定义来执行此操作:

CREATE TABLE Linq_TB
(
   url_id INT NOT NULL,
   Linq_id INT NOT NULL,
   Pg_Name NVARCHAR(50) NOT NULL,
   URL NVARCHAR(50) NOT NULL,

   CONSTRAINT PK_Link_TB PRIMARY KEY (url_id, Linq_id),
   CONSTRAINT FK_URL_TB_URL_ID FOREIGN KEY (url_id) REFERENCES URL_TB (url_id)
)
GO

CREATE TRIGGER tr_Linq_TB_InsertUpdate
ON Linq_TB
INSTEAD OF INSERT
AS
    INSERT INTO Linq_TB
    SELECT i.url_id,
        ISNULL(tb.Linq_id, 0)
            + row_number() over (partition by i.url_id order by (select 1)),
        i.Pg_Name, i.URL
    FROM inserted i
    LEFT OUTER JOIN 
            (
            SELECT url_id, MAX(Linq_ID) Linq_id
            FROM Linq_TB
            GROUP BY url_id
            ) tb ON i.url_id = tb.url_id
GO

定义您的CREATE TABLE列和约束。并且,触发器创建逻辑以在您的Linq_id列中为每个url_id.

请注意,触发器中的逻辑是不完整的。有几个问题没有解决:1)如果对url_id一行进行更改,触发器不会更新Link_id,以及 2)删除行将导致Linq_TB列序列出现间隙。

于 2012-12-29T20:03:27.673 回答