如何增加与另一列配对的标识列?

时间:2015-02-04 17:39:10

标签: sql sql-server database-administration

假设我想在SQL Server 2008 R2中创建一个表,如下所示(这可能是错误的,但它有助于说明这一点):

CREATE TABLE BANK_ACCOUNT
        (
            BankID INT NOT NULL,
            RecID INT IDENTITY(1,1) NOT NULL,
            IDValue varchar(100) NOT NULL,
        )  ON [PRIMARY]
GO

ALTER TABLE BANK_ACCOUNT
    ADD CONSTRAINT
                PK_BANK_ACCOUNT PRIMARY KEY CLUSTERED 
                (
                BankID,
                RecID
                ) ON [PRIMARY]

GO 我怎样才能这样做,以便每次我在表中插入记录时,RecID都会使用BankID适当增加。例如:

INSERT (BankID, IDValue) INTO BANK_ACCOUNT VALUES (1, "Val1")
INSERT (BankID, IDValue) INTO BANK_ACCOUNT VALUES (1, "Val2")
INSERT (BankID, IDValue) INTO BANK_ACCOUNT VALUES (2, "Val3")
INSERT (BankID, IDValue) INTO BANK_ACCOUNT VALUES (1, "Val4")

应该产生:

BankID | RecID | IDValue
   1      1        Val1
   1      2        Val2
   2      1        Val3
   1      3        Val4

1 个答案:

答案 0 :(得分:1)

改为创建View

CREATE TABLE BANK_ACCOUNT
  (
     Iden_Col INT IDENTITY(1, 1) NOT NULL,
     BankID   INT NOT NULL,
     IDValue  VARCHAR(100) NOT NULL,
  )

GO

INSERT INTO BANK_ACCOUNT
VALUES      (1,'Val1')

INSERT INTO BANK_ACCOUNT
VALUES      (1,'Val2')

INSERT INTO BANK_ACCOUNT
VALUES      (2,'Val3')

INSERT INTO BANK_ACCOUNT
VALUES      (1,'Val4')

go

CREATE VIEW BANK_ACCOUNT_View
AS
    SELECT Row_number()
            OVER(
                partition BY BankID
                ORDER BY Iden_Col) RecID,
            BankID,
            IDValue
    FROM   BANK_ACCOUNT 

select * FROM BANK_ACCOUNT_View