Should I use SqlString or string as parameter type to SQLCLR UDF's

荒凉一梦 提交于 2019-12-07 16:42:45

问题


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: use TimeSpan or TimeSpan?
  • DATETIME2: use DateTime or DateTime?
  • DATETIMEOFFSET: use TimeZoneOffset or TimeZoneOffset?
  • SQL_VARIANT: use object (NULL comes through as DbNull.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 and SqlCompareOptions (i.e. case sensitivity, accent sensitivity, etc) as defined by the default COLLATION of the database where the Assembly exists. Using string (or even SqlChars) would lose this info.
  • has methods to return a byte[] -- GetUnicodeBytes and GetNonUnicodeBytes -- whereas string has ToCharArray. NVARCHAR source data is encoded as UTF-16, which will use either 2 bytes or 4 bytes for each character, depending on the character.
  • properly handles T-SQL NULLs. This can be tested for via the IsNull boolean property (that all of the Sql* types have). When passing back as a return value or column value for a TVF, use the static property SqlString.Null (which all of the Sql* 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!