开发者

Cast column to dynamic size based on function argument

I开发者_开发百科 am trying to cast something to char(n) where n is a function argument

ALTER FUNCTION FixMe(@colName varchar, @width integer) RETURNS varchar
AS BEGIN
    RETURN CAST(@colName as char(@width))
END

This code is giving an error of

Incorrect syntax near '@width'.

I have also tried executing this with EXEC() via:

EXEC('set @retval = CAST(@colName as char(' + @width + '))')

But I then run in to

Invalid use of side-effecting or time-dependent operator in 'EXECUTE STRING' within a function.


Even if you did manage to get this to work in a function your RETURNS varchar statement would cause the result to be implicitly converted to varchar(1) on the way out.

I assume this is related to your previous question in which case this might work better for you.

ALTER FUNCTION FixMe(@colvalue VARCHAR(8000),
                     @width    INTEGER)
RETURNS VARCHAR(8000)
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
  BEGIN
      RETURN REPLACE(RTRIM(@colvalue), ' ', ' ') + 
               CASE
                   WHEN @width > LEN(@colvalue) 
                   THEN REPLICATE(' ', @width - LEN(@colvalue))
                   ELSE ''
               END        
  END 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜