[英]Increment value after 1000 without auto increment SQL
I want to increment User_ID
with respect to 1000. When a user enters the system, it will count it.我想相对于 1000 增加User_ID
。当用户进入系统时,它会计算它。 But I do not want to use identity increment because I already made ID identity increment.但是我不想使用身份增量,因为我已经进行了 ID 身份增量。 I do this just to be able to change it in backup at any time.我这样做只是为了能够随时在备份中更改它。 I create first user in SQL Server.我在 SQL Server 中创建了第一个用户。 Id is 1000. ID 为 1000。
Here is my code:这是我的代码:
string query1 = "ALTER TABLE UserInfo WHERE User_ID ORDER BY User_ID ASC SET IDENTITY_CACHE=ON";
int i;
cmd = new SqlCommand(query1);
conn.Open();
// I get an error here: "Connection property has not been initialized."
i = Convert.ToInt32(cmd.ExecuteScalar()) + 1;
conn.Close();
// "ALTER TABLE UserInfo WHERE User_ID ORDER BY User_ID ASC
string query = "INSERT INTO UserInfo(User_ID, Name, Surname, Birth_Date, Reg_Date) VALUES (@User_ID, @Name, @Surname, @Birth_Date, @Reg_Date)";
cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@User_ID", i);
cmd.Parameters.AddWithValue("@Name", TextBox1.Text);
cmd.Parameters.AddWithValue("@Surname", TextBox2.Text);
cmd.Parameters.AddWithValue("@Birth_Date", TextBox3.Text);
cmd.Parameters.AddWithValue("@Reg_Date", DateTime.Now.ToString());
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
the edited part is:编辑的部分是:
string query1 = "SELECT User_ID FROM UserInfo ORDER BY User_ID DESC"; string query1 = "SELECT User_ID FROM UserInfo ORDER BY User_ID DESC"; //User_ID is increment one more with respect to 1000 //User_ID 相对于 1000 再增加 1
cmd = new SqlCommand(query1, conn);
conn.Open();
int i = Convert.ToInt32(cmd.ExecuteScalar());
i = i + 1;
conn.Close();
IT WORKS有用
Your error description does not match your question title or description.您的错误描述与您的问题标题或描述不符。 You should fix that.你应该解决这个问题。
Cause of the problem : That being said, the SqlCommand
does require a connection and you never assign the connection to the command.问题的原因:话虽如此, SqlCommand
确实需要连接,而您从未将连接分配给命令。
Proposed solution : The easiest way would be using the constructor that requires also the connection SqlCommand(cmdText, connection) documentation .建议的解决方案:最简单的方法是使用还需要连接SqlCommand(cmdText, connection) 文档的构造函数。
cmd = new SqlCommand(query1, conn);
Not related to your problem but, it will likely bit your ass sonner or later, a couple things you should know/consider:与你的问题无关,但它可能会咬你的屁股或稍后,你应该知道/考虑的几件事:
The ALTER TABLE
statement does not allow the WHERE
clause, check the TSQL ALTER TABLE documentation . ALTER TABLE
语句不允许使用WHERE
子句,请查看TSQL ALTER TABLE 文档。 This has already been mentioned in the question comments by @KekuSemau. @KekuSemau 在问题评论中已经提到了这一点。
SqlConnection
does implement IDisposable
and your code does not call Dispose()
nor use the using statement . SqlConnection
确实实现了IDisposable
并且您的代码不调用Dispose()
也不使用using 语句。 I would advise using the using
statement.我建议使用using
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.