SQL Server query Insert into select and new data

时间:2018-02-03 07:46:22

标签: c# sql-server insert-into

I need some correction with my query in C# & SQL Server.

I have a table called LoggedIn with name, password and clockin columns. I want it to insert into the table where name and password is from another table AND the clockin is the current time now.

string belepve = "INSERT INTO LoggedIn VALUES (SELECT name, password FROM Login WHERE password =" + Kod.login1 +" ,@MyDate";

SqlCommand command4 = new SqlCommand(belepve, con);

command4.Parameters.AddWithValue("@MyDate", DateTime.Now);

And then I just Execute the query.

1 个答案:

答案 0 :(得分:0)

There are multiple issues here.

First is the second parameter should also go as SqlParameter.

Second you have missing parenthesis at end.

Third you would need to specify the column names in which values should go in LoggedIn table.

Your working code would be something like:

string belepve = @"INSERT INTO LoggedIn (name,password,LoginDate) 
                          VALUES (SELECT name,password,@MyDate 
                                  FROM Login 
                                  WHERE password =@Password
                                  )";

SqlCommand command4 = new SqlCommand(belepve, con);

 command4.Parameters.AddWithValue("@MyDate", DateTime.Now);
 command4.Parameters.AddWithValue("@Password", Kod.login1);

Assuming that you have columns in LoggedIn table as named name,password and LoginDate, you might need to adjust the column names which you have actually in your table.

If you have same number of columns which you are already selecting then you can do it more simple like following:

SELECT name,password,@MyDate 
INTO LoggedIn
FROM Login 
WHERE password =@Password

But you need to be careful in the order of columns selecting otherwise value might go in different column than in what is expected. Hope it helps.