What data type does the SQLCommand method ExecuteScalar() return?

后端 未结 3 1206
温柔的废话
温柔的废话 2021-01-18 16:08

In SQL Server, ID is a not null integer, and an identity.

When I run the following code, I get an InvalidCastException on the last line:

SqlCommand         


        
3条回答
  •  误落风尘
    2021-01-18 16:20

    SCOPE_IDENTITY() returns a decimal in code, otherwise known as NUMERIC(38,0) in TSQL.

    http://msdn.microsoft.com/en-us/library/ms190315.aspx

    So if you want a direct cast, you can do (int)(decimal)cmd.ExecuteScalar();. Note that a decimal to int conversion can lose information in the strictest sense, so just be advised. But with your identity column being an integer, the conversion will be safe.

提交回复
热议问题