Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Is the variable NVARCHAR(MAX)?

How can I get the actual type of a column or variable in t-sql?

I know about SQL_VARIANT_PROPERTY, but this fails miserably for NVARCHAR(MAX):

DECLARE @foo1 NVARCHAR(10) = N'a'
SELECT SQL_VARIANT_PROPERTY(@foo1, 'BaseType') --works fine
DECLARE @foo2 NVARCHAR(MAX) = N'a'
SELECT SQL_VARIANT_PROPERTY(@foo2, 'BaseType') --fails with an error:
--Operand type clash: nvarchar(max) is incompatible with sql_variant

Is there anything else that is able to tell me if a variable contains a value of the type NVARCHAR(MAX)?

Some background:

I am working on a procedure that should reorder the columns of a table: Rename the old table, create a new one, copy the data and drop the old one. In order to do this, all indexes, views, constraints, etc. need to be recreated on the new table.

I want to make sure that nothing gets lost in this automatic process. For that, I would like to copy most values from the relevant system-tables to a generic temp-table and compare the values after the reordering. This works perfectly fine now, but it fails when trying to detect the type of nvarchar(max)-columns.

like image 501
Andreas Avatar asked Jun 24 '26 19:06

Andreas


1 Answers

Andreas,

If you are looking to discover the data type and length of the column then you could use the following code. Note that -1 is used where (max) is stated in the schema. Add a WHERE clause in to specify table or column name

SELECT      tb.name TableName, cl.name ColumnName
            , cl.system_type_id, ty.name, cl.max_length
FROM        sys.columns cl
INNER JOIN  sys.tables tb ON tb.object_id = cl.object_id
INNER JOIN  sys.types ty ON cl.system_type_id = ty.system_type_id
ORDER BY    cl.max_length
like image 183
Tony Avatar answered Jun 27 '26 11:06

Tony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!