在SQL Server 2008中使用select语句和附加列插入表中

时间:2013-10-22 05:35:45

标签: sql-server sql-server-2008

我试图从select语句插入到表中,并使用类似的东西向行添加其他参数 -

SELECT 
        Appt_ID,
        Pracitioner_ID,
        Appt_Book_ID,
        Start_Time,
        UR_NO,
        [Type],
       [Description]
FROM @TempWaiting,
 @EndTime,
 @PatientID, 
 @Title, 
 @FirstName, 
 @LastName, 
 @Surname, 
 @DOB
INTO PS_WAITING_LIST(Appt_ID,   
        Pracitioner_ID,
        Appt_Book_ID,
        Start_Time,
        UR_NO,
        [Type],
        [Description],
        End_Time,
        Patient_ID, 
        Title,
        First_Name,
        Middle_Name,
        Surname,
        DOB)

这是在一个存储过程中,所有内容都是INTO之后的错误。

我也尝试将其重写为 -

insert into PS_WAITING_LIST (
        Appt_ID,    
        Pracitioner_ID,
        Appt_Book_ID,
        Start_Time,
        UR_NO,
        [Type],
        [Description],
        End_Time,
        Patient_ID, 
        Title,
        First_Name,
        Middle_Name,
        Surname,
        DOB)
SELECT 
        Appt_ID,
        Pracitioner_ID,
        Appt_Book_ID,
        Start_Time,
        UR_NO,
        [Type],
        [Description]
FROM @TempWaiting,
 @EndTime,
 @PatientID, 
 @Title, 
 @FirstName, 
 @LastName, 
 @Surname, 
 @DOB

这会抛出一个错误,指出select值的数量必须与insert列的数量相匹配。显然那不是。

我也试过Insert into table(col1,col2 ..)Select * from(select(...),col3,col9)

3 个答案:

答案 0 :(得分:18)

通常它的工作原理如下

insert into your_table (col1, col2, col3)
select some_column, @aVariable, 'static_string'
from another_table

答案 1 :(得分:2)

假设@tempWaiting是一个变量表,语句应该是这样的。

    insert into PS_WAITING_LIST (
    Appt_ID,    
    Pracitioner_ID,
    Appt_Book_ID,
    Start_Time,
    UR_NO,
    [Type],
    [Description],
    End_Time,
    Patient_ID, 
    Title,
    First_Name,
    Middle_Name,
    Surname,
    DOB)
SELECT 
    Appt_ID,
    Pracitioner_ID,
    Appt_Book_ID,
    Start_Time,
    UR_NO,
    [Type],
    [Description],
    @EndTime,
    @PatientID, 
    @Title, 
    @FirstName, 
    @LastName, 
    @Surname, 
    @DOB
FROM @TempWaiting

答案 2 :(得分:0)

您也可以尝试以下操作:

Insert Into CustomerNew (CustomerId, CustomerName) 
  SELECT CustID, Name
  FROM CustomerOld WHERE CustomerId Is not Null