what did I miss in the c# sql server Function during create function?

G. Gunn - fs 146 Reputation points
2021-09-27T06:36:32.757+00:00

for the created assembly Util
I tried to execute:
CREATE FUNCTION "dbo"."$formatListNormalized"(@list VARCHAR(max) )
RETURNS VARCHAR(max) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME Util.Util.formatListNormalize
GO

I got the message

Msg 6551, Level 16, State 2, Procedure $formatListNormalized, Line 1

CREATE FUNCTION for "$formatListNormalized" failed because T-SQL and CLR types for return value do not match.

and the corresponding clr function member is

[SqlFunction]
public static class Util
{
 ...
 [SqlFunction]
 public static string formatListNormalize(string list)
 {
 if (list == null) return null;
 list = list.Trim();
 if (list.Length < 1) return null;
 list = Regex.Replace(list, @"(?<comma>\s*[,]\s*)", ",").Trim();
 if (list.EndsWith(",")) list = list.Substring(0, list.Length - 1); /// 150821 added to remove trailing comma
 if (list.StartsWith(",")) list = list.Substring(1, list.Length - 1); /// 
 return list;
 }
 ...
}

I thought sql equivalent of c# string is varchar(max). why am I getting the return type mismatch error?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,795 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,301 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 112.5K Reputation points
    2021-09-27T08:44:09.017+00:00
    1 person found this answer helpful.
    0 comments No comments

  2. Timon Yang-MSFT 9,576 Reputation points
    2021-09-27T09:13:05.61+00:00

    String in C# only corresponds to nchar and nvarchar in Sql Server.

    I reproduced your problem using varchar and then switched to one of them and the problem disappeared.

    135497-capture.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.