Issues with getting uniqueidentifier auto generate in SQL on insert

自闭症网瘾萝莉.ら 提交于 2019-12-24 02:19:00

问题


I am trying to insert data from one table into another table. Table1 doesn't have a uniqueidentifier, but Table2 does. I have tried to insert using NEWID(), but I get a syntax error. Can someone please tell me what I am doing wrong?

INSERT INTO Table2 (NEWID(), [Item Description], [Item Cost])
SELECT Description, Cost FROM  Table1
WHERE Id = '1'

回答1:


In case Table2 is not yet created you can use this query:

SELECT
     NEWID() AS [ID]
    ,Description AS [Item Description]
    ,Cost AS [Item Cost]
INTO Table2
FROM Table1
WHERE Id = '1'

But, in case the schema for Table 2 has already been created, and it has a column for the identifier then you can use:

INSERT INTO Table2 ([ID], [Item Description], [Item Cost])
SELECT
   NEWID()
   , Description
   , Cost
FROM Table1
WHERE Id = '1'

But if you haven't created the schema for Table2 yet, then I recommend using the following code to create both the schema for the table and populate the data in it, using data from Table1.

CREATE TABLE Table2 (
    [ID] INT Identity
    ,[Item Description] AS NVARCHAR(MAX)
    ,[Item Cost] AS NUMERIC(18, 2))

INSERT INTO Table2([Item Description] , [Item Cost])
SELECT
    Description
    , Cost
FROM Table1
WHERE Id = '1'

Setting the ID column as Identity will auto-generate a UNIQUE identifier number for each row which you don't have to worry about populating. The number is incremental and it increments by default by 1 for each row, starting from 1.

You can also define a starting number and a incremental value by defining the [ID] column as [ID] INTEGER IDENTITY(1000, 2) and this will make the starting value 1000 and the increment will be 2 (but this is just FYI).



来源:https://stackoverflow.com/questions/27462490/issues-with-getting-uniqueidentifier-auto-generate-in-sql-on-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!