使用子查询插入以将多行插入数据库

时间:2015-03-23 16:46:05

标签: sql-server subquery insert-into

我正在努力制作一个'通知'查询目前正常工作。

我正在处理一个查询,该查询会将一个字符串添加到一个表格中,该表格会同时添加多个行,其中只有一列会在此批量插入中更改:

我目前有:

    public static void addNotification(string notification)
    {
        SqlConnection scon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);

        using (SqlCommand scmd = new SqlCommand())
        {
            scmd.Connection = scon;
            scmd.CommandType = CommandType.Text;
            scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged) VALUES ((SELECT Email FROM AspNetUsers), '" + notification + "' ,0)";
            scon.Open();
            int status = scmd.ExecuteNonQuery();
            scon.Close();
        }
    }

但是,在传递这样一个字符串时:"这是一个通知",它会出现以下错误:

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   一种表达。声明已经终止。

那么,有人可能会解释这个查询应该如何运行吗?

该表格包含以下列:

enter image description here

我理解' PK1'不是最好的做法,但这只是一个用于测试目的的表(它设置为自动递增)

那么,isAcknowledged应该设置为0,通知应该是这个字符串,并且应该从表AspNetUsers的每一行中选择电子邮件?

有人能够向我解释如何将这些数据添加到我的数据库中吗?

4 个答案:

答案 0 :(得分:2)

使用查询生成结果时,您不想使用VALUES。您可以将INSERT查询更改为:

INSERT INTO notificationAck (Email, Notification, isAcknowledged) 
SELECT Email, 'SOME STRING', 0 FROM AspNetUsers

翻译成代码的内容如下:

scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged) 
                    SELECT Email, '" + notification + "', 0 FROM AspNetUsers";

答案 1 :(得分:1)

这样的事情应该有效:

scmd.CommandText = "INSERT INTO notificationAck (Email, 
                                                 Notification, 
                                                 isAcknowledged) 
                    SELECT Email, '" + notification + "', 0
                    FROM AspNetUsers";

INSERT INTO SELECT不需要VALUES。因此,您只需使用SELECT语句从Email中检索AspNetUsers字段,再加上两个常量值。

答案 2 :(得分:0)

您的查询

SELECT Email FROM AspNetUsers
错误说明,

会返回多行。您需要更改它以便它只返回一行,例如:

SELECT TOP 1 Email FROM AspNetUsers

然后按以下方式更改命令

scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged) SELECT TOP 1 Email " + notification + "' ,0 FROM AspNetUsers'";

如果要插入多行,请从查询中删除前1位。

scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged) SELECT Email " + notification + "' ,0 FROM AspNetUsers'";

答案 3 :(得分:0)

  

如果您只想插入1行

,请在Sub Query中选择Top 1

INSERT INTO notificationAck (Email, Notification, isAcknowledged) 
VALUES ((SELECT top 1 Email FROM AspNetUsers), '" + notification + "' ,0)
  

如果要插入AspNetUsers中的所有行,请使用

 INSERT INTO notificationAck(Email,Notification, isAcknowledged) select 
 Email,''+notification +"',1 from AspNetUsers