【问题标题】:How to insert multiple rows with one insert statement如何用一个插入语句插入多行
【发布时间】:2014-03-20 20:36:13
【问题描述】:

我正在尝试将新行插入到我的数据库中。我有 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 个值,因此在这里实际上不起作用,有没有办法修改它以使其起作用?

【问题讨论】:

    标签: sql sql-server-2008


    【解决方案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】:
      insert into tblUsers (State,City,Code)
         Select 'IN','Indy',  UserCode 
         from tblAccounts 
         where UserCode in (Select UserCode 
                           from tblAccounts 
                           where State = 'IN')
      

      【讨论】:

        【解决方案3】:

        试试这个...

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

        【讨论】:

          【解决方案4】:

          查询:

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

          【讨论】:

            【解决方案5】:

            你只能从另一个表插入,像这样:

            insert into tblUsers (State,City,Code)
            SELECT * FROM table1
            

            【讨论】:

              猜你喜欢
              • 2018-05-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-01-04
              • 1970-01-01
              相关资源
              最近更新 更多