如何使用一个insert语句插入多行

时间:2014-03-20 20:36:13

标签: sql sql-server-2008

我正在尝试在我的数据库中插入新行。我需要插入155行。发生的事情是我正在添加基于现有帐户表的新用户。我有一个查询,列出了我需要添加到users表的新用户,但我不想输入155次插入。有更简单的方法吗?我已经看到插件中可以有多组“值”,但我不确定如何实现它。例如:

insert into tblUsers (State,City,Code)
Values ('IN','Indy',(select UserCode from tblAccounts where UserCode in(Select UserCode from tblAccounts where State = 'IN')))

我知道我的子查询将返回155个值,因此实际上不会在这里工作,有没有办法修改它以便它可以工作?

5 个答案:

答案 0 :(得分:1)

insert into tblUsers (State,City,Code)
   Select 'IN','Indy',  UserCode 
   from tblAccounts 
   where UserCode in (Select UserCode 
                     from tblAccounts 
                     where State = 'IN')

答案 1 :(得分:1)

试试这个:

INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE UserCode IN
    (SELECT UserCode
     FROM tblAccounts
     WHERE State = 'IN')

或更好的简化(不需要子查询):

INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE State = 'IN'

答案 2 :(得分:1)

试试这个......

INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode 
FROM tblAccounts 
WHERE UserCode IN (SELECT UserCode FROM tblAccounts WHERE State = 'IN')

答案 3 :(得分:1)

查询:

INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE State = 'IN'

答案 4 :(得分:0)

您只能从另一个表中插入,如下所示:

insert into tblUsers (State,City,Code)
SELECT * FROM table1
相关问题