简体   繁体   English

SQL Server查询插入到选择和新数据中

[英]SQL Server query Insert into select and new data

I need some correction with my query in C# & SQL Server. 我需要对C#和SQL Server中的查询进行一些更正。

I have a table called LoggedIn with name, password and clockin columns. 我有一个名为LoggedIn的表, LoggedIn包含名称,密码和LoggedIn列。 I want it to insert into the table where name and password is from another table AND the clockin is the current time now. 我希望它插入表中,其中名称和密码来自另一个表,而Clockin现在是当前时间。

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. 然后我只执行查询。

There are multiple issues here. 这里有多个问题。

First is the second parameter should also go as SqlParameter . 首先是第二个参数也应作为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. 第三,您需要指定要在LoggedIn表中LoggedIn值的列名称。

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. 假设您在LoggedIn表中具有名为namepasswordLoginDate的列,则可能需要调整表中实际具有的列名。

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. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM