1

I have a view that I'd like to create a table from in a query. I'd also like to add a primary key to the table, I was thinking something like the following:

SELECT *
, PK INT IDENTITY(1,1) PRIMARY KEY

INSERT INTO TESTTABLE

FROM my_view

SELECT * FROM TESTTABLE

DROP TESTTABLE

The above does not work, so...

a) is it possible and b) if so, how?

Thank you,

1
  • why don't you add the primary key column to the view itself and call it when needed? Commented Oct 22, 2015 at 19:55

1 Answer 1

1

You can use SELECT INTO to create new table and ALTER it to add PK:

SELECT *
INTO TESTTABLE
FROM my_view;

ALTER TABLE TESTTABLE
ADD PK INT IDENTITY(1,1) PRIMARY KEY;

SELECT *
FROM TESTTABLE;

DROP TABLE TESTTABLE;

SqlFiddleDemo

Sign up to request clarification or add additional context in comments.

8 Comments

When I check the syntax on this one I get the error of Unknown object 'TESTTABLE' used in CREATE, DROP or ALTER statement it seems to be only the DROP that is causing this problem as when I check syntax without it, its fine. Any thoughts?
@MCP_infiltrator Try with schema part dbo.TESTTABLE
negative...maybe I do not have DROP table permissions?
@MCP_infiltrator Check new demo, do you call it in stored procedure?
@MCP_infiltrator DROP TABLE smsdss.TESTTABLE; You need to specify what are you dropping :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.