我正在使用此代码:
SqlCommand cmd = new SqlCommand("insert into Inventory (ID,Group) SELECT ID from Inventory2 where Code='1' , 'Default'", con);
cmd.ExecuteNonQuery();
我收到错误','附近的语法不正确。
答案 0 :(得分:4)
您的查询应写为
string cmdText = @"insert into Inventory (ID,Group)
SELECT ID, 'Default'
from Inventory2
where Code='1'";
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.ExecuteNonQuery();
当然ID字段不应该是IDENTITY列,否则你不为它提供任何值,让db引擎计算它自己的值OR,如果你真的需要将自己的值添加到该列,你启用
SET IDENTITY_INSERT ON Inventory2
插入后,用OFF
将其停止如果你需要从两个表中插入相同数量的列,你可以写这个
string cmdText =@"insert into Inventory (ID,Group)
SELECT ID, 'Default' FROM Inventory2 WHERE Code='1'
UNION
SELECT ID, Category FROM INVENTORY3 WHERE Code='3'";
或者,如果字段数不同,您可以按照其他方法
string cmdText =@"insert into Inventory (ID,Group)
SELECT ID, 'Default' FROM Inventory2 WHERE Code='1';
insert into Inventory (ID,Group, Category)
SELECT ID, Group, Category FROM INVENTORY3 WHERE Code='3'";
答案 1 :(得分:2)
你应该写为:
SqlCommand cmd = new SqlCommand("insert into Inventory (ID,Group) SELECT ID, 'Default' from Inventory2 where Code='1' ", con);
cmd.ExecuteNonQuery();
答案 2 :(得分:2)
你应该选择这种方式选择两个值
SqlCommand cmd = new SqlCommand("
insert into Inventory (ID,Group)
SELECT ID, 'Default' from Inventory2 where Code='1' ", con);
答案 3 :(得分:2)
请尝试将此更改为以下内容..
"insert into Inventory (ID,Group) SELECT ID,'Default' from Inventory2 where Code='1'"
答案 4 :(得分:1)
你缺少一个n,它需要是conn