简体   繁体   English

T-SQL:变量NVARCHAR(MAX)?

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

How can I get the actual type of a column or variable in t-sql? 如何在t-sql中获取列或变量的实际类型?

I know about SQL_VARIANT_PROPERTY , but this fails miserably for NVARCHAR(MAX) : 我知道SQL_VARIANT_PROPERTY ,但是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) ? 还有什么能够告诉我变量是否包含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. 这现在完全正常,但在尝试检测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. 注意,使用-1,其中在模式中声明(max)。 Add a WHERE clause in to specify table or column name 添加WHERE子句以指定表或列名称

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 sql_variant不能存储nvarchar(max),Sql_variant支持字符串

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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