我有一个小问题,现在已经有一段时间了.
在这里:
是否可以临时禁用列ID上的Auto_Increment.
这样我就可以向表中添加一个新行,并在插入行时指定ID值.
然后最后再次启用Auto_Increment,让它像往常一样工作?
如果它可能我怎么能这样做?
表结构非常简单
列名(属性)
ID (Primary Key,Auto Increment,int,not null) Name (nvarchar(100),not null)
注意:
>表名是:人.
>我们还要考虑该表已有数据且无法更改.
>数据库服务器是sql Server CE.
>如果有任何帮助,sql命令将在C#程序中执行.
我真的希望它有可能,它会变得非常方便.
谢谢
编辑
sqlActions sqlActions = new sqlActions(); sqlCeCommand sqlCmd = new sqlCeCommand("SET IDENTITY_INSERT People ON",sqlActions.Connection()); try { sqlCmd.ExecuteNonQuery(); } catch (sqlCeException Error) { Console.WriteLine(Error.ToString()); } string query = "INSERT INTO People SET (ID,Nome) VALUES (@ID,@Nome)"; sqlCeCommand sqlInsert = new sqlCeCommand(query,sqlActions.Connection()); sqlInsert.Parameters.AddWithValue("@ID",15); sqlInsert.Parameters.AddWithValue("@Nome","Maria"); try { sqlInsert.ExecuteNonQuery(); } catch (sqlCeException Error) { Console.WriteLine(Error.ToString()); }
连接字符串正在工作,我已经尝试过了.
他报告说:
There was an error parsing the query.
[ Token line number = 1,Token line
offset
= 20,Token in error = SET ]
sqlActions sqlActions = new sqlActions(); sqlCeCommand sqlCmd = new sqlCeCommand("SET IDENTITY_INSERT People ON",sqlActions.Connection()); try { sqlCmd.ExecuteNonQuery(); string query = "INSERT INTO People (ID,@Nome)"; sqlCmd.CommandText = query; sqlCmd.Parameters.AddWithValue("@ID",15); sqlCmd.Parameters.AddWithValue("@Nome","Vania"); sqlCmd.ExecuteNonQuery(); } catch (sqlCeException Error) { Console.WriteLine(Error.ToString()); }
解决方法
我相信你可以使用
SET IDENTITY_INSERT
.我不确定这是否适用于所有版本.
更新2:
试试这个版本:
sqlActions sqlActions = new sqlActions(); sqlCeCommand sqlCmd = new sqlCeCommand("SET IDENTITY_INSERT People ON",sqlActions.Connection()); try { sqlCmd.ExecuteNonQuery(); string query = "INSERT INTO People (ID,@Nome)"; sqlCmd.CommandText = query; sqlCmd.Parameters.AddWithValue("@ID",15); sqlCmd.Parameters.AddWithValue("@Nome","Maria"); sqlCmd.ExecuteNonQuery(); } catch (sqlCeException Error) { Console.WriteLine(Error.ToString()); }