dbType NVarChar对此构造函数无效

P.B*_*key 22 c# sqlclr sql-server-2008

    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void MyMethod()
    {
        string connectionString = "context connection=true";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlMetaData[] metaData = {
                                         new SqlMetaData("Column1", System.Data.SqlDbType.NVarChar)
                                         ,new SqlMetaData("Column1", System.Data.SqlDbType.NVarChar)
                                     };
            SqlDataRecord record = new SqlDataRecord(metaData);
            record.SetString(0,"hello world");
            SqlContext.Pipe.SendResultsRow(record);
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我在SQL中运行该方法时

EXEC MyMethod

错误

消息6522,级别16,状态1,过程MyMethod,行0在执行用户定义的例程或聚合"MyMethod"期间发生.NET Framework错误:System.ArgumentException:dbType NVarChar对此构造函数无效.System.ArgumentException:在Microsoft.SqlServer.Server.SetaMetaData.ctor的Microsoft.SqlServer.Server.SqlMetaData.Construct(String name,SqlDbType dbType,Boolean useServerDefault,Boolean isUniqueKey,SortOrder columnSortOrder,Int32 sortOrdinal)(String name,SqlDbType dbType) )在WcfClrApps.MyNamespace.MyMethod()

如何归还我自己制作的唱片?我不想运行任何SQL.项目构建是为.NET 3.5设置的.SQL 2008 R2中不支持MSDN表示4.0.

P.B*_*key 39

这个问题有两个问题.1.最大长度是必需的.2. SendResultsStart()/ SendResultsEnd()是必需的.

    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void MyMethod()
    {
        string connectionString = "context connection=true";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlMetaData[] metaData = {
                                         new SqlMetaData("Column1", System.Data.SqlDbType.NVarChar, 100)//Max length has to be specified
                                         ,new SqlMetaData("Column1", System.Data.SqlDbType.NVarChar, 100)//same story
                                     };
            SqlDataRecord record = new SqlDataRecord(metaData);
            SqlContext.Pipe.SendResultsStart(record);//SendResultsStart must be called

            //create a row and send it down the pipe
            record.SetString(0,"hello world");
            SqlContext.Pipe.SendResultsRow(record);

            SqlContext.Pipe.SendResultsEnd();//End it out

        }
    }
Run Code Online (Sandbox Code Playgroud)

迭代的例子

  • 对于特定错误`dbType NVarChar对此构造函数无效`,只添加MaxLength参数可以解决问题.事实证明,在使用SqlDbType.NVarChar时,必须使用接受MaxLength参数的构造函数. (4认同)
  • @JamesFaix最大使用-1。即使使用Int32.MaxLength / 2也会导致溢出。 (3认同)