Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

sql - Execute table-valued function on multiple rows?

Given a table-valued function such as dbo.Split() from "T-SQL: Opposite to string concatenation - how to split string into multiple records", how do I pass multiple rows as arguments?

This works:

SELECT *
FROM dbo.Split
  (',', (SELECT myColumn FROM Stuff WHERE id = 22268))
WHERE ISNULL(s,'') <> ''

It returns:

pn          s
----------- -----------
1           22351
2           22354
3           22356
4           22357
5           22360

But this does not:

SELECT *
FROM dbo.Split
  (',', (SELECT myColumn FROM Stuff))
WHERE ISNULL(s,'') <> ''

Nor does this:

SELECT * FROM dbo.Split_temp(',', myColumn), Stuff

The docs say:

When a user-defined function that returns a table is invoked in the FROM clause of a subquery, the function arguments cannot reference any columns from the outer query.

The sort of result set I'm looking for would look something like:

id          pn          s
----------- ----------- -----------
22268       1           22351
22268       2           22354
22268       3           22356
22268       4           22357
22268       5           22360
24104       1           22353
24104       2           22355
24104       3           22356
24104       4           22358
24104       5           22360
24104       6           22362
24104       7           22364
.
.
.

Is there any way at all (aside from, of course, a cursor) to accomplish this?

(edit)

As requested by MarlonRibunal, a sample table to produce the above result looks like:

id          myColumn
----------- -------------------------------------------
22268       22351,22354,22356,22357,22360,
24104       22353,22355,22356,22358,22360,22362,22364,

id is an int; myColumn is a varchar(max).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OUTER APPLY:

SELECT Stuff.id
    ,Results.pn
    ,Results.s
FROM stackoverflow_454945 AS Stuff
OUTER APPLY dbo.Split(',', Stuff.myColumn) AS Results
WHERE ISNULL(Results.s,'') <> ''

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...