2017-01-09 3 views
1

SQLクエリからUserIdの戻り値をUsersid変数に保存します。値を取得できません.FYI UserNameはテキストです。C言語でSQL SELECTステートメントの戻り値を保存します。

int usersid; 
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) 
using (SqlCommand command = new SqlCommand()) 
{ 
    connection.Open(); 
    command.CommandText = @"Select UserId from [dbo].[User] where username= @username"; 

    command.Parameters.Clear(); 

    command.Parameters.AddWithValue("@username", currentUser.UserName); 
    usersid = (int)command.ExecuteScalar(); 

    command.CommandText = @"INSERT INTO [dbo].[ClientEmailConfirmation] ([JobNumber],[OrderNumber],[UserId]) VALUES 
                (@JobNumber,@OrderNumber,@UserId)"; 
    command.Parameters.Clear(); 
    command.Parameters.AddWithValue("@JobNumber", JobNumberTextBox.Text); 
    command.Parameters.AddWithValue("@OrderNumber", OrderNumberTextBox.Text); 
    command.Parameters.AddWithValue("@UserId", usersid); 
    command.ExecuteNonQuery(); 

} 

私は大いに おかげで、

+0

これはに答えている:[挿入された行のIDを取得するための最良の方法を?](http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row )と[挿入コマンドを実行し、Sqlで挿入されたIDを返す](http://stackoverflow.com/questions/18373461/execute-insert-command-and-return-inserted-id-in-sql) – Adrian

+0

この質問は、 [挿入された行のIDを取得する最善の方法?](http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row)と[Insert Insertコマンドを実行し、挿入されたIDをSql](http://stackoverflow.com/questions/18373461/execute-insert-command-and-return-inserted-id-in-sql) – Adrian

答えて

1
using (SqlCommand command = new SqlCommand()) 
{ 
    command.Connection = connection; 
    ... 
+0

これがどのように質問に答えるか分かりません。これはポスターが彼らが求めている 'UserId'を手に入れるのにどのように役立ちますか? – catfood

+0

@catfood - 'command.ExecuteScalar();'はエラーなく実行されます。 – Igor

+0

Ah。私はその部分を逃した。良い。あなたの答えはソリューションの一部であり、Mmcgowa3は残りを提供します。 – catfood

-1

がint型にスカラー結果変換し、あなたの助けに感謝:

  int userId = Convert.ToInt32(command.ExecuteScalar())); 
+0

申し訳ありませんが私の答えを更新しました。 – Mike

0

はじめに:私は2つを組み合わせることが答えだがまた、いくつかのベストプラクティスを提供しています。

元のコードサンプルには、SqlConnectionSqlCommandが接続されています。あなたは、次のコードスニペットを必要とする:

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) 
using (SqlCommand command = new SqlCommand()) 
{ 
    connection.Open(); 
    command.Connection = connection; 
    // Rest of code here. 
} 

私は個人的に空のコマンド・テキストでSqlCommandオブジェクトのコンストラクタで接続を割り当てることを好みます。常に接続がSqlCommandに割り当てられていることを確認します。詳細はhere on MSDNです。

UserId列が整数型であると仮定すると、結果のキャストは問題ありません。

usersid = (int)command.ExecuteScalar(); 

あなたはSqlParameterの独自のインスタンスをインスタンス化するのではなくSqlParameterCollectionオフAddWithValue()方法を使用する必要があります。あなたが相反するデータ型を持っている機会がない場合、AddWithValueは間違ったタイプを推測し、問題を診断するのが難しい場合があります。詳しくは、articleまたはMSDNをご覧ください。

command.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar) { Value = currentUser.UserName }); 
関連する問題