简体   繁体   中英

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.

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

sql_variant can not store nvarchar(max) and Sql_variant does support strings

it will not store this types also

varchar(max)
varbinary(max)
nvarchar(max)
xml
text

etc...

instead of go to

nvarchar(4000) but not nvarchar(max).
varchar(8000) but not varchar(max)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM