3

What is the difference between the Sqlxxx datatypes and their .NET equivalents?

For instance, why and when should I use SqlString and not string?

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.