views:

123

answers:

3

How to create t-sql scalar value function that input string multivalued and that sould return string1 + string2 + string3.

A: 

If you are not looking for this please let me know (Just an example)

First create a table with some values

like

create table tbl (id int, col1 varchar(50),col2 varchar(50), col3 varchar(50))
insert into tbl values(1,'colval1','colval2','colval3')


CREATE FUNCTION fn_TestFunc
(   
    @param1 int
)
RETURNS  varchar(max)
AS
BEGIN   
    declare @result varchar(max)

    select @result =  Col1+ ',' + Col2 + ',' + Col3
    from tbl t
    where t.ID = @param1

    return @result


END

To execute the function select dbo.fn_TestFunc(1)

Output:

Col1Val , Col2Val , Col3Val

1 more example

ALTER FUNCTION [dbo].[fn_TestFunc]
(
    -- Add the parameters for the function here
    @param1 int
)
RETURNS  nvarchar(max)
AS
BEGIN

    declare @result varchar(max)
    SELECT @result= 
    (
     SELECT 
      CAST(Col1 AS varchar(max)) + ',' + CAST(Col1 AS varchar(max)) + '|'
     from tbl t
                where t.ID = @param1
     FOR XML PATH ('')
    ) 
    return LEFT(@result,LEN(@result) - 1)
END

Output

Col1Val , Col2Val
priyanka.sarkar
Msg 208, Level 16, State 1, Line 1Invalid object name 'tbl'.
monkey_boys
Com on .. create a table by the name tbl with columns id(int), col1 (varchar), col2(varchar).. then run it will work
priyanka.sarkar
create table tbl( id int, col1 varchar(50),col2 varchar(50), col3 varchar(50))
priyanka.sarkar
A: 

Or are you looking for this(an example)

CREATE FUNCTION fn_MyFunc
(
    @param1 varchar(10)
)
RETURNS varchar(max)
AS
BEGIN

    declare @result varchar(max)
    set @result = @param1 + '-' + @param1 + '-' + @param1
    return @result
END

Output: test-test-test when executed with select dbo.fn_MyFunc('test')

priyanka.sarkar
A: 

Try the following:

CREATE FUNCTION fn_Concat
(   
    @string1 varchar(max),
    @string2 varchar(max),
    @string3 varchar(max)
)
RETURNS  varchar(max)
AS
BEGIN   
    declare @result varchar(max)

    Set @result =  @string1+ ',' + @string2 + ',' + @string3


    return @result


END

--SELECT dbo.fn_Concat('aa','bb','cc')
Himadri