Friday, 29 May 2009
StringFormat* and VARCHAR(MAX)
posted by Stefan Delmarco
The StringFormat* functions in the Fotia SQLCLR Library demonstrate some very interesting SQLCLR capabilities. In order to make the StringFormat* functions useful, they need to work with all data types being passed as arguments to the format. The natural C# solution is to use the object data type for the argument parameters:
21 [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true)]
22 public static SqlString FormatString2(SqlString format, object arg0, object arg1, object arg2)
23 {
The .NET object maps to sql_variant, making the TSQL function prototype:
1 create function dbo.FormatString2(@format nvarchar(max), @arg0 sql_variant, @arg1 sql_variant
2 ,@arg2 sql_variant)
3 returns nvarchar(max)
However, sql_variant comes with its own limitations. It isn’t compatible will all data types, specifically those that can exceed 8,o16 bytes. The StringFormat* functions therefore do not work with the varchar(max)-family of data types. Given that StingFormat*’s primary purpose is to make string manipulation easier I’ve added the StringFormatMax* family of functions that take all their arguments as SqlString and use nvarchar(max) as their prototype:
21 [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true)]
22 public static SqlString FormatStringMax2(SqlString format, SqlString arg0, SqlString arg1,
23 SqlString arg2)
24 {
TSQL prototype:
5 create function dbo.FormatStringMax2(@format nvarchar(max), @arg0 nvarchar(max), @arg1 nvarchar(max)
6 ,@arg2 nvarchar(max))
7 returns nvarchar(max)
StringFormatMax* can handle all the varchar(max)-like data types. However, it loses the ability to perform any data type specific formatting (like float precision, padding, etc.) as the arguments are converted to strings by SQL before being passed to the StringFormatMax* functions.
Labels: sqlclr
