SQL Fiddle
I'm trying without success to change an iterative/cursor query (that is working fine) to a relational set query to achieve a better performance.
What I have:
table1
| ID | NAME |
|----|------|
| 1 | A |
| 2 | B |
| 3 | C |
Using a function, I want to insert my data into another table. The following function is a simplified example:
Function
CREATE FUNCTION fn_myExampleFunction
(
@input nvarchar(50)
)
RETURNS @ret_table TABLE
(
output nvarchar(50)
)
AS
BEGIN
IF @input = 'A'
INSERT INTO @ret_table VALUES ('Alice')
ELSE IF @input = 'B'
INSERT INTO @ret_table VALUES ('Bob')
ELSE
INSERT INTO @ret_table VALUES ('Foo'), ('Bar')
RETURN
END;
My expected result is to insert data in table2 like the following:
table2
| ID | NAME |
|----|-------|
| 1 | Alice |
| 2 | Bob |
| 3 | Foo |
| 3 | Bar |
To achieve this, I've tried some CTEs (Common Table Expression) and relational queries, but none worked as desired. The only working solution that I've got so far was an iterative and not performatic solution.
My current working solution:
BEGIN
DECLARE
@ID int,
@i int = 0,
@max int = (SELECT COUNT(name) FROM table1)
WHILE ( @i < @max ) -- In this example, it will iterate 3 times
BEGIN
SET @i += 1
-- Select table1.ID where row_number() = @i
SET @ID =
(SELECT
id
FROM
(SELECT
id,
ROW_NUMBER() OVER (ORDER BY id) as rn
FROM
table1) rows
WHERE
rows.rn = @i
)
-- Insert into table2 one or more rows related with table1.ID
INSERT INTO table2
(id, name)
SELECT
@ID,
fn_result.output
FROM
fn_myExampleFunction (
(SELECT name FROM table1 WHERE id = @ID)
) fn_result
END
END
The objective is to achieve the same without iterating through the IDs.