diff --git a/src/SqlAsyncCollector.cs b/src/SqlAsyncCollector.cs index afb445c0..212d1d74 100644 --- a/src/SqlAsyncCollector.cs +++ b/src/SqlAsyncCollector.cs @@ -501,13 +501,17 @@ public static string GetColumnDefinitionsQuery(SqlObject table) { return $@" select - {ColumnName}, DATA_TYPE + + {ColumnName}, case - when CHARACTER_MAXIMUM_LENGTH = -1 then '(max)' - when CHARACTER_MAXIMUM_LENGTH <> -1 then '(' + cast(CHARACTER_MAXIMUM_LENGTH as varchar(4)) + ')' - when DATETIME_PRECISION is not null and DATA_TYPE not in ('datetime', 'date', 'smalldatetime') then '(' + cast(DATETIME_PRECISION as varchar(1)) + ')' - when DATA_TYPE in ('decimal', 'numeric') then '(' + cast(NUMERIC_PRECISION as varchar(9)) + ',' + + cast(NUMERIC_SCALE as varchar(9)) + ')' - else '' + when DATA_TYPE = 'json' then 'nvarchar(max)' + else DATA_TYPE + + case + when CHARACTER_MAXIMUM_LENGTH = -1 then '(max)' + when CHARACTER_MAXIMUM_LENGTH <> -1 then '(' + cast(CHARACTER_MAXIMUM_LENGTH as varchar(4)) + ')' + when DATETIME_PRECISION is not null and DATA_TYPE not in ('datetime', 'date', 'smalldatetime') then '(' + cast(DATETIME_PRECISION as varchar(1)) + ')' + when DATA_TYPE in ('decimal', 'numeric') then '(' + cast(NUMERIC_PRECISION as varchar(9)) + ',' + + cast(NUMERIC_SCALE as varchar(9)) + ')' + else '' + end end as {ColumnDefinition} from INFORMATION_SCHEMA.COLUMNS c diff --git a/test/Unit/SqlOutputBindingTests.cs b/test/Unit/SqlOutputBindingTests.cs index eb5dfccb..b5c98c05 100644 --- a/test/Unit/SqlOutputBindingTests.cs +++ b/test/Unit/SqlOutputBindingTests.cs @@ -70,5 +70,22 @@ public void TestAsBracketQuotedString(string s, string expectedResult) string result = s.AsBracketQuotedString(); Assert.Equal(expectedResult, result); } + + /// + /// Verifies that the column definitions query maps JSON columns to nvarchar(max) instead of + /// the invalid json(max) syntax. The native json data type does not accept a length specifier. + /// See: https://learn.microsoft.com/en-us/sql/t-sql/data-types/json-data-type + /// + [Fact] + public void TestGetColumnDefinitionsQueryMapsJsonToNvarcharMax() + { + var table = new SqlObject("dbo.TestTable"); + string query = SqlAsyncCollector.TableInformation.GetColumnDefinitionsQuery(table); + + // The query should map json columns to nvarchar(max) + Assert.Contains("when DATA_TYPE = 'json' then 'nvarchar(max)'", query); + // The query should not produce 'json(max)' which is invalid SQL syntax + Assert.DoesNotContain("json(max)", query); + } } }