用于视图查询操作的唯一键

时间:2017-12-05 20:12:57

标签: sql sql-server tsql

我在sql server中有这个视图表,我想让它成为单独列中每条记录的唯一键。

如何将其作为单独列中每条记录的唯一键?比如索引

这是创建视图的代码

SELECT     'order' AS type, id AS id, id_customer, amount AS debit, 0 AS credit, order_date AS date, '....' AS description
FROM         dbo.Orders
UNION ALL
SELECT     'receipt' AS type, id AS id, id_customer, 0 AS debit, amount AS credit, receipt_date AS date, 'cash' AS description
FROM         dbo.receipts

我在使用此代码询问此演示文稿 但是我有一个问题,当有发票和收据类似的ID号重复每一次两次,所以我想要一个唯一的密钥在以下代码中进行比较

declare @id_customer int 
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)
               from initial b
               where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit)
  from initial r
)

 select [Operation type] = type,
        reference_no = r.id,
        [description],
        [Debit] = debit,
        [Credit] = credit,
        [Balance] = b.balance
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 order by r.[date]

1 个答案:

答案 0 :(得分:-1)

如果您想用新的唯一密钥区分您的记录(据我所知),那么您应该使用NEWID进行选择,以获得UnionAll查询的唯一密钥:

declare @id_customer int 
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)
               from initial b
               where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit)
  from initial r
)

 select NEWID(), -- this is a new generated unique key
        [Operation type] = type,
        reference_no = r.id,
        [description],
        [Debit] = debit,
        [Credit] = credit,
        [Balance] = b.balance
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 order by r.[date]