Extended TYPE_NAME function that includes datalength(包含数据长度的扩展 TYPE_NAME 函数)
问题描述
我正在考虑创建一个格式的函数
I'm thinking of creating a function of the format
FULL_TYPE_NAME(type_id, max_length)
以字符串格式返回数据类型和长度,例如:
that returns both the datatype and length in string format eg.:
FULL_TYPE_NAME (231,-1)
会回来:
nvarchar(max)
在我这样做之前,我想检查一下 tsql 是否已经有这样的功能(我还没有找到),或者是否有好心人有一个现成的我可以使用的功能.如果没有,那么我会写一个并在这里发布.
Before I do this I wanted to check if tsql already has such a function (I haven't found one) or whether some kind soul out there has a ready made one that I can use. If not, then I'll write one and post it here.
提前致谢.
推荐答案
粗略的开始是这样的:
CREATE FUNCTION udf_GetDataTypeAsString
(
@user_type_id INT ,
@Length INT
)
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE @ReturnStr VARCHAR(50)
IF @Length = -1
SELECT @ReturnStr = UPPER(name) + '(MAX)'
FROM sys.types
WHERE user_type_id = @user_type_id
ELSE
SELECT @ReturnStr = UPPER(name) + '(' + CONVERT(VARCHAR, @Length) + ')'
FROM sys.types
WHERE user_type_id = @user_type_id
RETURN @ReturnStr
END
GO
SELECT dbo.udf_GetDataTypeAsString(167, -1)
--#### Returns VARCHAR(MAX)
SELECT dbo.udf_GetDataTypeAsString(231, 24)
--#### Returns NVARCHAR(24)
请注意,这仅适用于 char 数据类型 &只处理长度,如果你想使用精度(小数等),你需要实现更多的逻辑
Note that this is only really good for char data types & only handles length, You'd need to implement a bit more logic if you want to use precision (decimals etc)
此外,您可能希望添加验证以仅允许特定用户类型的 -1 长度
Also, you may want to add validation to only allow -1 length on certain user types
(出于好奇——你为什么要这样做?)
(For the sake of curiosity – why do you want to do this?)
这篇关于包含数据长度的扩展 TYPE_NAME 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:包含数据长度的扩展 TYPE_NAME 函数
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
