简体   繁体   中英

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. But I do not want to use identity increment because I already made ID identity increment. I do this just to be able to change it in backup at any time. I create first user in SQL Server. Id is 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"; //User_ID is increment one more with respect to 1000

            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.

Proposed solution : The easiest way would be using the constructor that requires also the connection SqlCommand(cmdText, connection) documentation .

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:

  1. The ALTER TABLE statement does not allow the WHERE clause, check the TSQL ALTER TABLE documentation . This has already been mentioned in the question comments by @KekuSemau.

  2. SqlConnection does implement IDisposable and your code does not call Dispose() nor use the using statement . I would advise using the using statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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