将动态表名称传递给 SQL 函数并返回逗号分隔的字符串
mytable 结构:id int,lookuptablename varchar
1, 'lookuptable1'
2, 'lookuptable2'
lookuptable1:id int,item varchar
1, 'item1 from lkt1'
2, 'item2 from lkt1'
lookuptable2:id int,item varchar
1, 'item1 from lkt2'
2, 'item2 from lkt2'
查询:
SELECT GetDelimitedList(lookuptablename) FROM mytable;
预期结果:
1,2~item1 from lkt1,item2 from lkt1
1,2~item1 from lkt2,item2 from lkt2
我有一直在努力寻找一种方法来以各种方式实现这一目标,但就是无法弄清楚。
mytable structure: id int, lookuptablename varchar
1, 'lookuptable1'
2, 'lookuptable2'
lookuptable1: id int, item varchar
1, 'item1 from lkt1'
2, 'item2 from lkt1'
lookuptable2: id int, item varchar
1, 'item1 from lkt2'
2, 'item2 from lkt2'
Query:
SELECT GetDelimitedList(lookuptablename) FROM mytable;
Expected result:
1,2~item1 from lkt1,item2 from lkt1
1,2~item1 from lkt2,item2 from lkt2
I have been struggling to find out a way to accomplish this in various ways but just couldn't figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个解决方法。 UDF 将不起作用。也许是 CLR,但不是本机 SQL UDF。
首先创建此过程,它将表混合成一行
然后使用此 SQL 批处理生成相当于
SELECT GetDelimitedList(tablename) FROM mytable;
使用的示例表:
A workaround. UDFs won't work. Maybe CLR, but not native SQL UDF.
First create this proc, which mashes a table into a single row
Then use this SQL batch to produce the output equivalent to
SELECT GetDelimitedList(tablename) FROM mytable;
Sample tables used:
为了后代的利益,动态 Sql 通常应该是可参数化的(尽管这里没有必要)并通过 sp_executesql 执行。有关 EXEC 与 sp_executesql 的完整详细信息可以在这篇(优秀)文章中找到:
http://www.sommarskog。 se/dynamic_sql.html
将 Erland 的错误处理建议与编写动态存储过程的建议相结合,生成类似于以下内容的模板:
在问题的情况下并以 @RichardTheKiwi 的答案为基础,我们最终得到公认的功能与上面的过程等效的过程,但更容易调试:
For posterity's sake, dynamic Sql should generally be parameterizeable (even though it's unnecessary here) and executed via sp_executesql. Full details on EXEC vs. sp_executesql can be found in this (excellent) article:
http://www.sommarskog.se/dynamic_sql.html
Combining Erland's suggestions for error handling with his suggestions for writing dynamic stored procedures, yields a template similar to the following:
In the case of the question and to build upon @RichardTheKiwi's answer, we end up with an admittedly functionally equivalent procedure to the one above that is a little more debuggable: