I wish to write a User Defined Function that will return a char value that is sized according to an input parameter. I'm not sure it is even possible, but I thought I'd ask anyway.
So I have a query that looks like this:
SELECT
Convert(char(10), SUBSTRING('Field1', 1, 10)) AS Field1,
Convert(char(20), SUBSTRING('Value2', 1, 20)) AS Field2
I'd like to write a function that will make it possible to write this:
SELECT
fn_ConvertAndPad('Field1', 10) AS Field1,
fn_ConvertAndPad('Field2', 20) AS Field2
Is there a way to specify the output as char(10) or char(20)?
This was my (obviously failed) attempt:
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
And no, I can't just return a varchar, I need a padded string for a flat text output.