0

我希望编写一个用户定义的函数,它将返回一个根据输入参数调整大小的 char 值。我不确定这是否可能,但我想我还是会问。

所以我有一个看起来像这样的查询:

SELECT 
Convert(char(10), SUBSTRING('Field1', 1, 10)) AS Field1,
Convert(char(20), SUBSTRING('Value2', 1, 20)) AS Field2

我想写一个函数,可以这样写:

SELECT 
fn_ConvertAndPad('Field1', 10) AS Field1,
fn_ConvertAndPad('Field2', 20) AS Field2

有没有办法将输出指定为 char(10) 或 char(20)?

这是我(显然失败)的尝试:

ALTER FUNCTION [dbo].[fn_ConvertAndPad] 
(
    -- Add the parameters for the function here
    @input varchar(100),
    @length int
)
RETURNS char
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result char

    -- Add the T-SQL statements to compute the return value here
    DECLARE @blanks char(100)
    SET @blanks = ' '
    SELECT @Result = SUBSTRING(@input + @blanks, 1, @length)

    -- Return the result of the function
    RETURN @Result
END

不,我不能只返回一个 varchar,我需要一个填充字符串来输出纯文本。

4

1 回答 1

2

我不确定您是否可以使用用户函数来执行此操作,因为我估计您将需要执行动态 SQL 来获得您想要的,即在操作期间定义返回类型。据我所知,您可以在过程中执行此操作,但不能在函数中执行此操作。

create proc [dbo].[p_ConvertAndPad] 
(
    @input varchar(100),
    @length int
)
AS


BEGIN

    declare @SQL varchar(256);

    set @SQL =  'DECLARE @Result char(' + cast(@length as varchar) + ');

SELECT @Result = SUBSTRING(''' + @input + ''', 1, ' +  cast(@length as varchar) + ')

Select @Result as [char(' + cast(@length as varchar) + ')]'

    Exec (@SQL)
END
GO

exec p_ConvertandPad 'Whoa I can change dynamically',  10  -- Change number to any number you want and it should change the return type.

编辑不确定这是否对您来说足够明确但关闭:

create function [dbo].[f_ConvertAndPad] ( @string varchar(256), @len int)
returns sql_variant
as 

BEGIN
  declare @var sql_variant;

  select @var = cast(left(@string, cast(SQL_VARIANT_PROPERTY(@len,'maxlength') as int)) as char);

  return @var

END
GO

select [dbo].[f_ConvertAndPad]('Hey what are you looking at', 3), sql_variant_property([dbo].[f_ConvertAndPad]('Hey what are you looking at', 3), 'basetype')
于 2013-01-25T00:54:11.460 回答