简体   繁体   中英

Store value in a variable after using select statement

How to store the value of the PolicyID returned from database in an integer variable in C# ?

I am using SQL server 2005.

        System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
        dataConnection.ConnectionString =
            @"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";

        System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
        dataCommand.Connection = dataConnection;
        dataCommand.CommandText = ("select PolicyID from Policies where PolicyID=(select max(PolicyID) from Policies)");



        dataConnection.Open();
        dataCommand.ExecuteNonQuery();
        dataConnection.Close();

Please suggest.

Thanks.

Use the SqlCommand.ExecuteScalar method, like this:

command.CommandText = @"select max(PolicyID) from Policies";
int maxPolicyId = (int)command.ExecuteScalar();

Also, if you're doing this to insert a new Policy row with a unique ID, you must not do it like this, because it's entirely possible that a different Policies row will be inserted between the select and the insert.

Instead, use an IDENTITY column or a UNIQUEIDENTIFIER column.

EDIT : To use this in your code, do this:

int maxId;
using (SqlConnection dataConnection = new SqlConnection(@"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True"))
using (SqlCommand dataCommand = 
        new SqlCommand("select max(PolicyID) from Policies", dataConnection)) {

    dataConnection.Open();
    maxId = Convert.ToInt32(dataCommand.ExecuteScalar());
}
DECLARE @id INTEGER
SELECT @id=PolicyID FROM ...

Did you just insert a new record into that policy table and now you want the ID given? Then instead of a max(), use

SELECT SCOPY_IDENTITY()

to get the value that was assigned to your record, not to a record that happened to be inserted moments later.

You can also use SELECT IDENT_CURRENT('Policies') to get the value that was created for your record. To learn more about the differences between SCOPE_IDENTITY() AND IDENT_CURRENT('tablename') , check out this link .

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