4

I created one function, That function return the table values like below

CREATE FUNCTION dbo.splitText(@strArgs VARCHAR(4000))
    RETURNS @tab TABLE
    (
        [Key] VARCHAR(255) NOT NULL,
        Value VARCHAR(4000) NOT NULL
    )
    AS
    BEGIN

INSERT INTO @tab VALUES('Key1', 'Value1')
INSERT INTO @tab VALUES('Key2', 'Value2')

RETURN
END
GO

OUtput:
Key Value
*************
Key1    Value1
Key2    Value2

The second function i need,is to return the table values from the above fuction.

CREATE FUNCTION dbo.TableValuedParameterExample11()
RETURNS  @TmpTable1  table (Value VARCHAR(4000) NOT NULL) 
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 Select * into TmpTable1  from (Select value from dbo.Splittext('Test'))  aa

 RETURN  
END
GO

after finishing the functions,i am running the below query.

Select * from TmpTable1.

Output i need

Value 
********
Value1
Value2

I need this out put.

But I got error

Invalid use of a side-effecting operator 'SELECT INTO' within a function.
3
  • 2
    You need to use a stored procedure. DDL is not allowed in functions Commented Sep 30, 2016 at 6:18
  • its work but i need to call the function many times. So need to over come i can use "Select * from TmpTable1" this query @Nadeem Commented Sep 30, 2016 at 6:36
  • If the TmpTable1 in the second function is a base table you cannot insert any record into it because functions can't you need to use a stored procedure, it will work with the declared table. Commented Sep 30, 2016 at 6:38

1 Answer 1

7

When you write select * into [table]... you must be sure the [table] doesnot exist. use insert into [table] select ... instead. also, you need a @ when you deal with variable or function table:

CREATE FUNCTION dbo.TableValuedParameterExample11()
RETURNS  @TmpTable1  table (Value VARCHAR(4000) NOT NULL) 
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 INSERT INTO
    @TmpTable1([Value])
 SELECT 
    value 
 FROM 
    dbo.SplitArgs('Test'))  aa

 RETURN  
END
GO
Sign up to request clarification or add additional context in comments.

4 Comments

After run this function. Can i use the Temptable. Like this "Select * from @TmpTable1". Tedo.G
No you cannot, but you can do a JOIN to this function like: SELECT * FROM SomeTable s INNER JOIN dbo.TableValuedParameterExample1 () d ON d.[value]=s.[value]
Pls explain with above sample @gofr1
@Meline I just have :) in my previous comment with query example. Also you can declare @temptable and insert from function into it like INSERT INTO @temptable SELECT * FROM dbo.TableValuedParameterExample1 () or use #temptable like SELECT * INTO #temptanle FROM dbo.Table aluedExample1 () and then work with temtable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.