Rushikesh Korgaonkar
Rushikesh Korgaonkar

Reputation: 191

How to change identity specification for a column using sql query?

How to change identity specification for a column using sql query ? Only using c# coding. Pls Help. Here i want to add one more column as PaperId while creating new table in following code. I need to assign columns property as identity specification yes and identity increment 1.

if (rbtnEng.Checked == true)
{
    con.Open();
    char[] arr = new char[] { 'n', 'g', 'l', 'i', 's', 'h' };
    string str = "CREATE TABLE " + Label1.Text.Trim() + txtpaperset.Text.Trim() 
    + rbtnEng.Text.TrimEnd(arr) + "(" + "quesNo int NOT NULL PRIMARY KEY, " 
    + "question varchar(1000) NOT NULL," + "ansA varchar(500) NOT NULL, " 
    + "ansB varchar(500) NOT NULL, " + "ansC varchar(500) NOT NULL, " 
    + "ansD varchar(500) NOT NULL, " + "rightAns varchar(50) NOT NULL " + ")";
    SqlCommand cmd = new SqlCommand(str, con);
    cmd.ExecuteNonQuery();
    Label2.Text = Label1.Text + txtpaperset.Text + rbtnEng.Text.TrimEnd(arr);
    lblerrormsg.Text = "PaperSet Created Sucessfully!";
    txtpaperset.ReadOnly = true;
    btnpaper.Enabled = false;
    rbtnEng.Enabled = false;
    rbtnMar.Enabled = false;
    UpdatePanel2.Visible = true;
    txtQuestNo.Text = Convert.ToString(1);
    con.Close();
}

else if....

Upvotes: 0

Views: 2603

Answers (2)

Nathan
Nathan

Reputation: 1090

First, this is bad. Don't add so many strings like this; use string.Format().

string str = string.Format("CREATE TABLE {0}{1}{2} (" 
+ "quesNo int NOT NULL PRIMARY KEY, question varchar(1000) NOT NULL, " 
+ "ansA varchar(500) NOT NULL, ansB varchar(500) NOT NULL, " 
+ "ansC varchar(500) NOT NULL, ansD varchar(500) NOT NULL, " + 
+ "rightAns varchar(50) NOT NULL )",
Label1.Text.Trim(),
txtpaperset.Text.Trim(),
rbtnEng.Text.TrimEnd(arr));

But that's just my opinion.

Here's how to create an identity column.

PaperId int identity(1,1)

Just add it to your str string.

Upvotes: 2

Void Ray
Void Ray

Reputation: 10219

If you just need to add an identity column to the create table script, then here is an example:

create table Data
(
Id int identity(1,1) NOT NULL
)

Upvotes: 1

Related Questions