包含数据长度的扩展 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?)
相关文章