I was looking for a CLR function that will do the same thing as String.Format in C#. As an example, I would like to do the following through a CLR function:
String.Format("My name is {0}, and I live in {1}",myName, cityName)
I would like to be able to pass variable number of parameters after the first parameter, which would be as many place holders are specified in the first parameter to this CLR function. Anyone has any idea on what would be the C# code for such a CLR function?
I’m looking for the same thing. I came across these two sites: http://www.fotia.co.uk/fotia/Blog/2009/05/indispensable-sql-clr-functions.html & http://stringformat-in-sql.blogspot.com/.
The first uses a CLR function, the other uses a stored procedure.
In the first post, the writer says that UDF parameters aren’t optional so you can’t have variable number of params (at least the way he is doing it). He just creates a different function with the number or args he will need.
[SqlFunction(DataAccess = DataAccessKind.None)] public static SqlString FormatString1(SqlString format, object arg0, object arg1) { return format.IsNull ? SqlString.Null : string.Format(format.Value, SqlTypeToNetType(arg0, arg1)); }EDIT : This is how I solved this problem for me.
Using the stored procedure from the second article, I created this function to format the text for me using a pivot table. Our database is setup with a table
dbo.[Rules]that has a column[Description]that has a string that needs to be formatted such as: “NET INCOME MARGINAL (${0} TO BELOW ${1})”. We then have a 1-many tabledbo.[RuleParameters]with a row for each value that needs to be substituted. The columndbo.[SortOrder]specifies which order the arguments go in. This function will work for AT MOST 4 arguments which is the most that we have.EDIT #2: Adding more examples
Format string function:
Here is how I call the stored procedure:
Now I can just call the function like this to get everything formatted nicely for me! Here is sample usage with the results:
Normally when calling this, I wouldn’t join on the [RuleParameters] table, but I did in this case so that you can see the data before and after in one data set.