这就是我最终的结果(使用 SQL Server 2014)
CREATE FUNCTION dbo.GetTypeDeclaration(@schema AS VARCHAR(MAX), @table AS VARCHAR(MAX), @column AS VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @type as SYSNAME
DECLARE @typeDeclaration as VARCHAR(MAX)
DECLARE @maxLength AS SMALLINT
DECLARE @precision AS TINYINT
DECLARE @scale AS TINYINT
SELECT @type = ty.name, @maxLength = c.max_length, @precision = c.precision, @scale = c.scale
FROM sys.tables t
INNER JOIN sys.columns c ON t.object_id = c.object_id
INNER JOIN sys.types ty ON ty.user_type_id = c.user_type_id
WHERE t.schema_id = SCHEMA_ID(@schema) AND t.name = @table AND c.name = @column
IF @maxLength <> -1 AND @type IN ('nchar', 'nvarchar', 'nvarbinary')
BEGIN
SET @maxLength = @maxLength / 2
END
IF @type IN ('binary', 'char', 'nchar')
BEGIN
SET @typeDeclaration = @type + '(' + CAST(@maxLength AS VARCHAR) + ')'
END
ELSE IF @type IN ('datetime2', 'datetimeoffset', 'time')
BEGIN
SET @typeDeclaration = @type + '(' + CAST(@scale AS VARCHAR) + ')'
END
ELSE IF @type IN ('nvarchar', 'nvarbinary', 'varchar', 'varbinary')
BEGIN
SET @typeDeclaration = @type + '(' + CASE WHEN @maxLength = -1 THEN 'max' ELSE CAST(@maxLength AS VARCHAR) END + ')'
END
ELSE IF @type IN ('decimal', 'numeric')
BEGIN
SET @typeDeclaration = @type + '(' + CAST(@precision AS VARCHAR) + ', ' + CAST(@scale AS VARCHAR) + ')'
END
ELSE
BEGIN
SET @typeDeclaration = @type
END
RETURN @typeDeclaration
END