質問

GUIDを作成してDBに保存します。

C#では、Guid.NewGuid()を使用してGUIDを作成できます。これにより、128ビット整数が作成されます。 SQL Serverには、巨大な16進数を保持するuniqueidentifier列があります。

C#とSQL ServerのGUIDを適切に連携させるための良い/推奨される方法はありますか? (つまり、Guid.New()を使用してGUIDを作成し、nvarcharまたは他のフィールドを使用してデータベースに保存するか、またはSQL Serverが他の何らかの方法で期待する16進数のフォームを作成します)

役に立ちましたか?

解決

SQLは、GUIDを文字列として期待しています。 C#の次のコードは、Sqlが予期している文字列を返します。

"'" + Guid.NewGuid().ToString() + "'"

次のようなもの

INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')

はSQLでの表示です。

他のヒント

パラメータ化されたクエリを使用してGUIDを挿入する方法を示すコードスニペットを次に示します。

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using(SqlTransaction trans = conn.BeginTransaction())
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
            cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
            cmd.ExecuteNonQuery();
            trans.Commit();
        }
    }

SqlDbType .UniqueIdentifier

メソッドは次のようになります(ただし、唯一のパラメーターがGuidである場合):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

また参照:SQL Serverの uniqueidentifier

データ型がuniqueidentifierのフィールドのデータベースに保存します。

// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("@statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("@read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("@write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC

myCommand.ExecuteNonQuery();

myCommand.Dispose();
myConnection.Close();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top