C# guid and SQL uniqueidentifier

前端 未结 5 1778
你的背包
你的背包 2020-11-27 15:37

I want to create a GUID and store it in the DB.

In C# a guid can be created using Guid.NewGuid(). This creates a 128 bit integer. SQL Server has a uniqueidentifier

5条回答
  •  时光说笑
    2020-11-27 16:42

    You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

    Your method may look like this (provided that your only parameter is the 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();
        }
    }

    See also: SQL Server's uniqueidentifier

提交回复
热议问题