我有以下用户定义的函数:
CREATE FUNCTION dbo.GetConcatenatedWithKeyAsInt32(@Values dbo.IndexValue READONLY)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
SELECT
[Id],
-- The definition of [Names] is not really important to this question!
[Names] = stuff((
select ', ' + Value
from @Values AS xt
where xt.Id = t.Id
for xml path(''), TYPE
).value('.[1]','varchar(max)'), 1, 2, '')
FROM @Values AS t GROUP BY t.Id);
该参数是用户定义的表类型:
CREATE TYPE IndexValue AS TABLE ( Id int, Value VARCHAR(max) );
我正在努力调用此函数。
我发现了一些示例,人们在实际的物理表(或视图)上调用了这样的函数,但是可以肯定的是,可以直接在select表达式中使用它,不是吗?
我试过了:
SELECT *
FROM dbo.GetConcatenatedWithKeyAsInt32(
SELECT c.Id AS Id, a.City AS value
FROM Customers c
JOIN Addresses a ON c.Id = a.CustomerId
);
SQL Server不喜欢这样:
Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near ')'
这可能吗?如果是这样,正确的语法是什么?
还是我真的需要为它创建一个临时表或视图
SELECT c.Id AS Id, a.City AS value
FROM Customers c
JOIN Addresses a ON c.Id = a.CustomerId
第一?
最佳答案
在回答您的特定问题时:
这可能吗?如果是这样,正确的语法是什么?还是我真的需要首先创建一个临时表或视图?
SQL Server不支持您尝试执行此操作的方式。方式是分配用户定义类型的变量,然后将值SELECT
分配到该变量中:
declare @values as dbo.IndexValue
insert into @values
SELECT c.Id AS Id, a.City AS value
FROM Customers c
JOIN Addresses a ON c.Id = a.CustomerId
select * from dbo.GetConcatenatedWithKeyAsInt32(@values)
我相信从SQL Server 2008开始就支持此功能。
它可能类似于创建临时表,但是我相信这是实现您所要求的唯一方法。