如何确定(运行时)t-sql 中的类型是否是固定长度?
如果类型(例如 nvarchar 或 int)是固定长度或不是通过查询某些系统表,是否可以使用 t-sql 找出运行时?
我需要这样做的原因是我需要生成 sql 代码运行时并且需要生成一些声明(DECLARE @foo SOMETYPE(LENGTH)
或 DECLARE @foo SOMETYPE
)取决于某些列的类型(在设计时未知)。
我当前的赌注是,我可以检查 sys.all_columns.max_length = sys.types.max_length 是否,如果是,则假设它是固定长度的(因为 max_length 似乎有特殊代码 (-1),至少对于 nvarchar)。
Is it possible to find out runtime using t-sql if a type (e.g. nvarchar or int) is fixed-length or not by querying some system-table?
The reason I need to do this is that I need to generate sql-code runtime and need to generate some declarations (DECLARE @foo SOMETYPE(LENGTH)
or DECLARE @foo SOMETYPE
) depending on the type of some columns (that are unknown at design-time).
My current bet is that I can check if sys.all_columns.max_length = sys.types.max_length
and if so assume that it is fixed-length (since max_length
seems to have a special code (-1), at least for nvarchar).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以查看 information_schema.columns。 如果字符类型列有最大长度,则将在character_maximum_length中指定,数字字段的精度在numeric_ precision中定义。 有几点说明,据我所知,int 类型始终是 4 个字节,而且,任何 var 类型根据定义都不是固定长度,并且仅存储最大长度,如果 nvarchar(10) 持有 2字符串,只存储2个字符。 因此,要检测固定长度字符串,您需要寻找 char 或 nchar 类型。
You can look at information_schema.columns. If a character typed column has a max length it will be specified in character_maximum_length, numeric fields have their precision defined in numeric_precision. A couple notes, to the best of my knowledge the int type is always 4 bytes, also, any of the var types are by definition not fixed length, and only store up to their max length, if a nvarchar(10) holds a 2 character string, it only stores 2 characters. So to detect fixed length strings, you would be looking for the char or nchar types.
是的,这是可能的。 查看内置存储过程 sp_columns 的代码,了解如何执行此操作。
Yes, it's possible. Look at the code for the built-in stored proc sp_columns to see how to do this.