1

I'm running a SQLCLR function with SqlConnection("context connection=true").

In some cases, I get the exception

System.Data.SqlClient.SqlException (0x80131904)
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnectionSmi.EventSink.DispatchMessages(Boolean ignoreNonFatalMessages)
at System.Data.SqlClient.SqlDataReaderSmi.InternalRead(Boolean ignoreNonFatalErrors)
at ObjDb.Functions.ObjDb(String db, String schema, String obj, String col, String val)

ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:200,State:4,Class:25

That happens every time with same query at same record number.

With connection

SqlConnection(@"Server=" + @"localhost\sqldeveloper16" + ";Database=" + db + ";Integrated Security=true;connect Timeout = 50")

I never get this error, and all is fine.

I don't understand why.

Then I tried same CLR on SQL Server 2008 and there are no problem...what do I have to check?!?!

Could this be a SQL Server 2016 bug?!

This my class

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
using Newtonsoft.Json;
using System.Xml.Linq;
using System.IO;
using System.Linq;
using System.Text;

namespace ObjDb
{
    public partial class Functions
    {
        [SqlFunction
        (
            //DataAccess = DataAccessKind.Read,//serve x accedere alle tabelle del db, altrimenti accede solo a qlle di sistema...
            SystemDataAccess = SystemDataAccessKind.Read,
            FillRowMethodName = "columns_ok",
            TableDefinition = "c1 nvarchar(max), node nvarchar(max)"
        )
        ]

        public static IEnumerable ObjDb(String db, String schema, String obj, String col, String val)
        {
            List<String> rows = new List<String>();//List<Object[]> rows = new List<Object[]>();
            //List<tuple.t2<String, String>> rows = new List<tuple.t2<String, String>>();

            SqlCommand command = null;// = new SqlCommand(query, conn);
            SqlConnection conn = null;// new SqlConnection("context connection=true");

            try
            {
                conn = new SqlConnection("context connection=true");//new SqlConnection(@"Server=" + @"localhost\sqldeveloper16" + ";Database=" + db + ";Integrated Security=true;connect Timeout = 50"); //new SqlConnection("context connection=true");//
                conn.Open();

                String query;
                StringBuilder sb = new StringBuilder();
                sb.Append("where 0=0");

                if ((col != null && !col.Equals("")) && (val != null && !val.Equals("")))
                {
                    String[] cols = col.Split(',');
                    String[] vals = val.Split(',');

                    for (int i = 0; i < Math.Min(cols.Length, vals.Length); i++)
                    {
                        sb.Append(" and [").Append(cols[i]).Append("]='").Append(vals[i].Replace("'", "''")).Append("'");
                    }
                    //filter = "where 0=0 " + sb.ToString();
                    //filter = "where [" + col + "]='" + val + "'";
                }
                //estrazione inline dell xml (un xml x ogni riga)
                //"BINARY BASE64" -> https://stackoverflow.com/questions/8801697/xml-export-via-bcp-bulk-export - bug 2008R2, converte il varbinary in ascii
                query =
                "select (select t.* for xml raw('root'),BINARY BASE64) " +
                "from [" + db + "].[" + schema + "].[" + obj + "] t " +
                sb.ToString(); ;//filter;

                command = new SqlCommand(query, conn);
                //command.CommandTimeout = 0;
                SqlDataReader dr = command.ExecuteReader();

                while (dr.Read())
                {
                    //rows.Add(new tuple.t2<String, String>("", (String)dr[0]));
                    rows.Add((String)dr[0]);
                }
                return rows;
            }
            catch (Exception e)
            {
                rows.Add(e.ToString().Substring(0, Math.Min(4000, e.ToString().Length)));
                return  rows;
            }
            finally
            {
                if (command != null)
                    command.Dispose();
                if (conn != null)
                    conn.Close();
            }
        }
        private static void columns_ok(object resultObj, out SqlString node)
        {
            //String res = (String)resultObj;

            node = (String)resultObj;
        }
    }
}

and then from Sql

select *
from dbo.objdb('test','sys','all_columns',null,null)

result is (5248 records and last contains the exception, i posted only last 3):

<root object_id="-103402673" name="similarity_index_page_count" column_id="4" system_type_id="127" user_type_id="127" max_length="8" precision="19" scale="0" is_nullable="1" is_ansi_padded="0" is_rowguidcol="0" is_identity="0" is_computed="0" is_filestream="0" is_replicated="0" is_non_sql_subscribed="0" is_merge_published="0" is_dts_replicated="0" is_x005F_xml_document="0" xml_collection_id="0" default_object_id="0" rule_object_id="0" is_sparse="0" is_column_set="0" generated_always_type="0" generated_always_type_desc="NOT_APPLICABLE" is_hidden="0" is_masked="0"/>
<root object_id="-103085222" name="database_id" column_id="1" system_type_id="56" user_type_id="56" max_length="4" precision="10" scale="0" is_nullable="0" is_ansi_padded="0" is_rowguidcol="0" is_identity="0" is_computed="0" is_filestream="0" is_replicated="0" is_non_sql_subscribed="0" is_merge_published="0" is_dts_replicated="0" is_x005F_xml_document="0" xml_collection_id="0" default_object_id="0" rule_object_id="0" is_sparse="0" is_column_set="0" generated_always_type="0" generated_always_type_desc="NOT_APPLICABLE" is_hidden="0" is_masked="0"/>
System.Data.SqlClient.SqlException (0x80131904)     at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)     at System.Data.SqlClient.SqlInternalConnectionSmi.EventSink.DispatchMessages(Boolean ignoreNonFatalMessages)     at System.Data.SqlClient.SqlDataReaderSmi.InternalRead(Boolean ignoreNonFatalErrors)     at ObjDb.Functions.ObjDb(String db, String schema, String obj, String col, String val)  ClientConnectionId:00000000-0000-0000-0000-000000000000  Error Number:200,State:4,Class:25

thank in advance!!

UPDATE: i don't know why, but the problem is the column "collation_name" ONLY ON SQL 2016.

i tried to remove it from the query and no exceptions...

8
  • Can you post your SQLCLR code as well as the full error message. Error 0x80131904 can be a couple of things, one being that the server cannot be found, but it can also be other errors. Also, what do you mean with "the same query at same record number" (same query I understand but same record number???). Aug 18, 2017 at 13:58
  • so, clr give me a number of record (for ex 5249) each time for that query and then throw an exception. i tried with 2 sql 2016 and same problem, with 2008r2 all fine...
    – elle0087
    Aug 18, 2017 at 14:06
  • What exact query is it executing? Please post at least that query into the question, but better would be to also include the .NET code. Aug 18, 2017 at 14:09
  • Without having looked too much into it, I do think that your error-handling masks the actual error. Aug 18, 2017 at 14:18
  • this is what .net give me...i think is a server setting, that happens on sql 2016 istance, not on 2008. i tried 3 sql 2016 instances, give error only on these...i don't know what i have to check...
    – elle0087
    Aug 18, 2017 at 14:35

2 Answers 2

3

The error is coming from one particular row in sys.system_columns, which is one of the two internal tables queried in the sys.all_columns system catalog view.

This error also appears to only happen if the collation_name field is used in a query selecting from either sys.system_columns or sys.all_columns.

Testing subsets of rows, I was able to determine that the error only occurs for one row. That object is:

sys.pdw_nodes_pdw_physical_databases

This row is not present in SQL Server 2012 (I have not tested anything besides 2012 SP3 and 2016 SP1), and there are no errors there at all.

The O.P. mentioned that this error only occurs when the collation_name field is selected. Looking at that field for that particular row, it is NULL. Certainly there is nothing wrong with a NULL since so many other rows shown NULL for collation_name. What is different for this one row is that the datatype is sysname, which is an alias for NVARCHAR(128), which is a string type and hence should always have a non-NULL Collation. I'm not sure how it is that this column, physical_name, has a NULL Collation, but it is the only string column with a NULL Collation in SQL Server 2016, and there are none in SQL Server 2012.

Why the error? Well, the real error is:

Msg 6522, Level 16, State 1, Line 406
A.NET Framework error occurred during execution of user-defined routine or aggregate "ObjDb":
  System.Data.SqlClient.SqlException:
  System.Data.SqlClient.SqlException:
    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
    at System.Data.SqlClient.SqlInternalConnectionSmi.EventSink.DispatchMessages(Boolean ignoreNonFatalMessages)
    at System.Data.SqlClient.SqlDataReaderSmi.InternalRead(Boolean ignoreNonFatalErrors)
    at System.Data.SqlClient.SqlDataReaderSmi.Read()
    at ObjDb.Functions.ObjDb(String db, String schema, String obj, String col, String val)

Notice how there is no actual error message! Weird. Not sure how that happens, but the collation_name field is actually the following expression:

convert(sysname, ColumnPropertyEx(object_id, name, 'collation')) AS collation_name

The ColumnPropertyEx function is undocumented, so there isn't much to go on.

I suspect that this is a bug, of sorts, where ColumnPropertyEx raises a low-level error, low enough to not to show up as an error in SSMS. However, the in-process connection (i.e. Context Connection = true) seems to be very sensitive and actually catches whatever is happening with ColumnPropertyEx.

Now, avoiding this should be a simple matter of adding the following condition to the WHERE clause if the schema name is sys and the object_name is all_columns or system_columns:

NOT (user_type_id IN (231, 256) AND collation_name IS NULL)

However, since those are views, it seems to process all rows before apply those filters.

SO, the one way that I found around this is to filter on the id fields using the following:

NOT (t.[object_id] = -103085222 AND t.[column_id] = 2)

The only real problem now is that I don't know if that object_id is the same across all versions of SQL Server 2016, nor in SQL Server 2017 (I haven't checked there yet).

What / Where is the real bug?

While it seems like the ColumnPropertyEx function should probably not be behaving as it is, I think the primary problem is that the 3 columns for pdw_nodes_pdw_physical_databases should be returning from sys.all_columns in the first place. pdw_nodes_pdw_physical_databases isn't even available outside of Azure SQL Data Warehouse and Parallel Data Warehouse. In fact, it is strange enough that the object name pdw_nodes_pdw_physical_databases is returned by the OBJECT_NAME function, yet does not show up in sys.all_objects ;-).

2
  • hi, so thanks for the answer and the precision with which you wrote! but, my last doubt is why in "Context Connection = true" sql raise exception instead in SSMS. because if i exec the query "select collation_name from test.sys.all_columns" in SSMS is fine, in CLR not, but fin in CLR with a new connection like "SqlConnection(@"Server=" + @"localhost\sqldeveloper16" + ";Database=" + db + ";Integrated Security=true;connect Timeout = 50")"... what i want to say is, the result is correct in SSMS or the exception is not caught and the result has less records as really should has?
    – elle0087
    Aug 21, 2017 at 7:31
  • FYI I stumbled across this too, and chased the wrong things, until I realized this is a client/driver problem. It happens with SSMS 16, for example, but not any newer version. sqlblog.org/2019/12/18/metadata-meets-metadata Dec 18, 2019 at 17:31
0

i don't know the problem, so my work around is to add a new parameter where define the columns to extract.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
using Newtonsoft.Json;
using System.Xml.Linq;
using System.IO;
using System.Linq;
using System.Text;

namespace ObjDb
{
    public partial class Functions
    {
        [SqlFunction
        (
            //DataAccess = DataAccessKind.Read,//serve x accedere alle tabelle del db, altrimenti accede solo a qlle di sistema...
            SystemDataAccess = SystemDataAccessKind.Read,
            FillRowMethodName = "columns_ok",
            TableDefinition = "c1 nvarchar(max), node nvarchar(max)"
        )
        ]

        public static IEnumerable ObjDb(String db, String schema, String obj, String col, String col, String val)
        {
            List<String> rows = new List<String>();//List<Object[]> rows = new List<Object[]>();
            //List<tuple.t2<String, String>> rows = new List<tuple.t2<String, String>>();

            SqlCommand command = null;// = new SqlCommand(query, conn);
            SqlConnection conn = null;// new SqlConnection("context connection=true");

            try
            {
                conn = new SqlConnection("context connection=true");//new SqlConnection(@"Server=" + @"localhost\sqldeveloper16" + ";Database=" + db + ";Integrated Security=true;connect Timeout = 50"); //new SqlConnection("context connection=true");//
                conn.Open();

                String query;
                StringBuilder sb = new StringBuilder();
                sb.Append("where 0=0");

                if ((col != null && !col.Equals("")) && (val != null && !val.Equals("")))
                {
                    String[] cols = col.Split(',');
                    String[] vals = val.Split(',');

                    for (int i = 0; i < Math.Min(cols.Length, vals.Length); i++)
                    {
                        sb.Append(" and [").Append(cols[i]).Append("]='").Append(vals[i].Replace("'", "''")).Append("'");
                    }
                    //filter = "where 0=0 " + sb.ToString();
                    //filter = "where [" + col + "]='" + val + "'";
                }

            String headers;

            if (col != null && !col.Equals(""))
            {
                headers = col;
            }
            else
            {
                headers = "t.*";
            }
                //estrazione inline dell xml (un xml x ogni riga)
                //"BINARY BASE64" -> https://stackoverflow.com/questions/8801697/xml-export-via-bcp-bulk-export - bug 2008R2, converte il varbinary in ascii
                query =
                "select (select " + headers + " for xml raw('root'),BINARY BASE64) " +
                "from [" + db + "].[" + schema + "].[" + obj + "] t " +
                sb.ToString(); ;//filter;

                command = new SqlCommand(query, conn);
                //command.CommandTimeout = 0;
                SqlDataReader dr = command.ExecuteReader();

                while (dr.Read())
                {
                    //rows.Add(new tuple.t2<String, String>("", (String)dr[0]));
                    rows.Add((String)dr[0]);
                }
                return rows;
            }
            catch (Exception e)
            {
                rows.Add(e.ToString().Substring(0, Math.Min(4000, e.ToString().Length)));
                return  rows;
            }
            finally
            {
                if (command != null)
                    command.Dispose();
                if (conn != null)
                    conn.Close();
            }
        }
        private static void columns_ok(object resultObj, out SqlString node)
        {
            //String res = (String)resultObj;

            node = (String)resultObj;
        }
    }
}

what i tried:

select *
from dbo.objdb('test','sys','all_columns',null,null,null)

error

select *
from dbo.objdb('test','sys','all_columns','collation_name',null,null)

error

select *
from dbo.objdb('test','sys','all_columns','object_id,name,column_id,system_type_id,user_type_id,max_length,precision,scale,is_nullable,is_ansi_padded,is_rowguidcol,is_identity,is_computed,is_filestream,is_replicated,is_non_sql_subscribed,is_merge_published,is_dts_replicated,is_xml_document,xml_collection_id,default_object_id,rule_object_id,is_sparse,is_column_set,generated_always_type,generated_always_type_desc,encryption_type,encryption_type_desc,encryption_algorithm_name,column_encryption_key_id,column_encryption_key_database_name,is_hidden,is_masked',null,null)

(all columns without "collation_name") FINE!

 select *
 from dbo.objdb('test','sys','columns','collation_name',null,null)

FINE O.o

3
  • Problem has to do with sys.system_columns catalog view. I am looking further into it. Aug 18, 2017 at 15:36
  • yes, with select * from dbo.objdb('test','sys','system_columns','collation_name',null,null) i have same problem...but why in sql 2016 only?!?! and why not with sys.columns??
    – elle0087
    Aug 18, 2017 at 15:38
  • I found it...will write it up soon...it's one particular row in sys.system_columns. Aug 18, 2017 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.