Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Identity column to a view in SQL Server 2008

This is my view:

Create View [MyView] as
(
Select col1, col2, col3 From Table1
UnionAll
Select col1, col2, col3 From Table2
)

I need to add a new column named Id and I need to this column be unique so I think to add new column as identity. I must mention this view returned a large of data so I need a way with good performance, And also I use two select query with union all I think this might be some complicated so what is your suggestion?

like image 906
Saeid Avatar asked Apr 30 '12 10:04

Saeid


People also ask

How do you create an identity column in a view in SQL Server?

Values of the ORDER BY columns are unique. [if column 1 is unique, row_number should be stable] Combinations of values of the partition column and ORDER BY columns are unique. [if you need 10 columns in your order by to get unique... go for it to make row_number stable]"

How do I add an identity column to an existing column?

You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.

Can we add column in view?

To modify a view Select or clear the check boxes of any elements you wish to add or remove. Right-click within the diagram pane, select Add Table..., and then select the additional columns you want to add to the view from the Add Table dialog box.

How do you set an identity column in SQL?

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value. The setting of SET IDENTITY_INSERT is set at execute or run time and not at parse time.


1 Answers

Use the ROW_NUMBER() function in SQL Server 2008.

Create View [MyView] as

SELECT ROW_NUMBER() OVER( ORDER BY col1 ) AS id, col1, col2, col3
FROM(
    Select col1, col2, col3 From Table1
    Union All
    Select col1, col2, col3 From Table2 ) AS MyResults
GO
like image 113
Daniel P Avatar answered Oct 05 '22 05:10

Daniel P