通过更改一列的值将一些表从一个表插入另一个表

时间:2013-12-02 17:44:03

标签: sql sql-server import

我有一张这样的表:

CREATE TABLE [dbo].[Question] (
    [QuesID]    INT            IDENTITY (1, 1) NOT NULL,
    [Body]      NVARCHAR (MAX) NULL,
    [O1]        NVARCHAR (MAX) NULL,
    [O2]        NVARCHAR (MAX) NULL,
    [O3]        NVARCHAR (MAX) NULL,
    [O4]        NVARCHAR (MAX) NULL,
    [UserID]    NVARCHAR (50)  NULL,
    [QuesDate]  DATETIME       NULL,
    PRIMARY KEY CLUSTERED ([QuesID] ASC)
);

我想

select * from Question where UserID=N'admin'

然后将我选择的内容插入此表,但将UserID从admin更改为另一个值。请注意,我不需要选择QuesID,因为它是PRIMARY KEY。

3 个答案:

答案 0 :(得分:3)

insert into Question ([Body], [O1], [O2], [O3], [O4], [UserID])
select [Body], [O1], [O2], [O3], [O4], 'newUserID' 
from Question 
where UserID = N'admin'

答案 1 :(得分:0)

insert ... select语句中,您可以轻松地用字面值替换列:

insert  YourTable
        (UserID, col1, col2, ...)
select  N'anothervalue'
,       col1
,       col2
,       ...
from    YourTable
where   UserID = N'admin'

答案 2 :(得分:0)

使用insert . . . select是适用于大多数数据库的标准SQL。以下是一个使用表格格式的示例:

insert into Question(Body, O1, O2, O3, O4, UserId, QuesDate)
    select Body, O1, O2, O3, O4, N'NewValue' as UserId, QuesDate
    from Question
    where UserId = N'admin';