问题
What is the difference between the Sqlxxx datatypes and their .NET equivalents?
For instance, why and when should I use SqlString
and not string
?
回答1:
Whenever possible, you should use the SqlTypes
types for SQLCLR method parameters. There are only 4 SQL Server datatypes that do not have a matching Sql*****
type:
TIME
: useTimeSpan
orTimeSpan?
DATETIME2
: useDateTime
orDateTime?
DATETIMEOFFSET
: useTimeZoneOffset
orTimeZoneOffset?
SQL_VARIANT
: useobject
(NULL
comes through asDbNull.Value
)
For more info, see the following MSDN page: Mapping CLR Parameter Data
Some differences between SqlString
and string
(that are important in certain situations) are that SqlString
:
- retains the encoding as defined by the default COLLATION of the database where the Assembly exists, and
- contains properties describing the
LCID
andSqlCompareOptions
(i.e. case sensitivity, accent sensitivity, etc) as defined by the default COLLATION of the database where the Assembly exists. Usingstring
(or evenSqlChars
) would lose this info. - has methods to return a
byte[]
-- GetUnicodeBytes and GetNonUnicodeBytes -- whereasstring
hasToCharArray
.NVARCHAR
source data is encoded asUTF-16
, which will use either 2 bytes or 4 bytes for each character, depending on the character. - properly handles T-SQL
NULL
s. This can be tested for via theIsNull
boolean property (that all of theSql*
types have). When passing back as a return value or column value for a TVF, use the static propertySqlString.Null
(which all of theSql*
types have).
When it comes to sending in large values in NVARCHAR(MAX)
and VARBINARY(MAX)
parameters, you can actually stream the values from SQL Server into SQL Server's CLR by using the SqlChars
and SqlBytes
types, respectively. There are some use cases where streaming is much more efficient (assuming you don't need the entire value at one time). Also, if the parameter is never accessed, then none of the data is sent over at all, unlike when using SqlString
and SqlBinary
, respectively.
Related information can be found in an article I wrote for a series on SQLCLR: Stairway to SQLCLR Level 5: Development (Using .NET within SQL Server) (free registration is required).
回答2:
A big difference is the null handling and collation. Look at the below link. I suggest using the sqlclr types for parameters and return types. You can typically work with these types in the whole function body.
http://msdn.microsoft.com/en-us/library/ms131049(v=sql.100).aspx
来源:https://stackoverflow.com/questions/9511885/should-i-use-sqlstring-or-string-as-parameter-type-to-sqlclr-udfs