Search code examples
sql-serversubqueryinsert-into

Insert Into with subquery to insert multiple rows into database


I am struggling to generate a 'notifications' query to work correctly at the moment.

I'm working on a query that will add a string to a table in which will add multiple rows at once, with only one column of which will be changed in this 'bulk insert':

I currently have:

    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();
        }
    }

However, on passing this a string like: "this is a notification", it comes up with the following error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.

So, could someone possibly explain how this query should be run?

The table has the columns:

enter image description here

I understand the 'PK1' isn't the best of practises, but this is only a table for testing purposes (it's set to auto increment)

So, the isAcknowledged should be set to 0, the notification should be this string, and the email should be selected from each row of the table AspNetUsers?

Would anyone e able to explain to me how I should go about adding this data into my db?


Solution

  • Something like this should work:

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

    INSERT INTO SELECT does not require VALUES. Hence, you only have to use a SELECT statement that retrieves Email field from AspNetUsers plus two constant values.