如何将值从另一个表插入到一个表中

时间:2015-07-30 09:59:55

标签: sql sql-server

我有两个表,即table1table2具有相同的结构,我想将table1的所有值插入table2。这些表包含两个图像类型列。我尝试了这个查询,但无法成功。

declare @imagepan varbinary(max)
declare @imagecheque varbinary(max)

set @imagepan=(select panid from table1 where Emp_code='E001')
set @imagecheque=(select cancel_checqe from table1 where Emp_code='E001')
insert into table2 
(transno, Emp_code, PanNo, panid, panext, entdt_pan, banknm, 
cancel_checqe, chqExt, entDt_bnk, Acc_No, IFSC, Cheque_nm, status_pan1, 
status_pan, status_bnk1, status_bnk, userid, entdt, panModify_by, 
panModify_on, bnkModify_by, bnkModify_on) 
values(select transno, Emp_code, PanNo, @imagepan, panext, entdt_pan, 
banknm, @imagecheque, chqExt, entDt_bnk, Acc_No, IFSC, Cheque_nm, 
status_pan1, status_pan, status_bnk1, status_bnk, userid, entdt, 
panModify_by, panModify_on, bnkModify_by, bnkModify_on from table1 where Emp_code='E001')

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

删除'values'关键字

insert into table2 (transno, Emp_code, PanNo, panid, panext, entdt_pan, 
                    banknm, cancel_checqe, chqExt, entDt_bnk, Acc_No, 
                    IFSC, Cheque_nm, status_pan1, status_pan, 
                    status_bnk1, status_bnk, userid, entdt, panModify_by, 
                    panModify_on, bnkModify_by, bnkModify_on) 
    select 
        transno, Emp_code, PanNo, @imagepan, panext, entdt_pan, 
        banknm, @imagecheque, chqExt, entDt_bnk, Acc_No, 
        IFSC, Cheque_nm, status_pan1, status_pan, 
        status_bnk1, status_bnk, userid, entdt, panModify_by, 
        panModify_on, bnkModify_by, bnkModify_on 
    from 
        table1 
    where 
        Emp_code = 'E001';

答案 1 :(得分:0)

只需删除values (并在结尾处关闭)

DECLARE @imagepan VARBINARY(MAX);
DECLARE @imagecheque VARBINARY(MAX);

SET @imagepan = (SELECT panid FROM table1 WHERE Emp_code = 'E001');
SET @imagecheque = (SELECT cancel_checqe FROM table1 WHERE Emp_code = 'E001');

INSERT INTO table2 (transno, Emp_code, PanNo, panid, panext, entdt_pan, 
banknm, cancel_checqe, chqExt, entDt_bnk, Acc_No, IFSC, Cheque_nm, 
status_pan1, status_pan, status_bnk1, status_bnk, userid, entdt, 
panModify_by, panModify_on, bnkModify_by, bnkModify_on) 
SELECT transno, Emp_code, PanNo, @imagepan, panext, entdt_pan, 
banknm, @imagecheque, chqExt, entDt_bnk, Acc_No, IFSC, Cheque_nm, 
status_pan1, status_pan, status_bnk1, status_bnk, userid, entdt, 
panModify_by, panModify_on, bnkModify_by, bnkModify_on 
FROM table1 
WHERE Emp_code='E001';