我创建了一个用户定义的表类型:
CREATE TYPE dbo.ListTableType AS TABLE(
ITEM varchar(500) NULL
)
我在一个函数中利用它:
CREATE FUNCTION dbo.fn_list_to_string
(
@LIST dbo.ListTableType READONLY
)
RETURNS varchar(max)
AS
BEGIN
DECLARE @RESULT varchar(max)
SET @RESULT = ''
DECLARE @NL AS CHAR(2) = CHAR(13) + CHAR(10)
SELECT @RESULT = @RESULT + ITEM + @NL FROM @LIST
SET @RESULT = SUBSTRING(@RESULT, 1, LEN(@RESULT) - 1)
RETURN @RESULT
END
最后,我尝试在一个简单的选择中使用这个函数:
SELECT
P.PROGRAM_ID,
PROGRAM_NAME,
PROGRAM_DESC,
P.STATUS_ID,
STATUS_DESC,
P.CONTACT_SID,
I.FIRST_NAME + ' ' + I.LAST_NAME as CONTACT_NAME,
P.CLARITY_ID,
dbo.fn_list_to_string(
( SELECT CONVERT(varchar,CLARITY_ID) as ITEM
FROM dbo.MUSEUM_PROGRAM_PROJECTS as A
JOIN dbo.MUSEUM_PROJECTS as B on B.PROJECT_ID = A.PROJECT_ID
WHERE PROGRAM_ID = P.PROGRAM_ID )
) as PROJECT_CLARITY_IDS
FROM dbo.MUSEUM_PROGRAMS as P
LEFT JOIN dbo.MUSEUM_PROGRAM_STATUS_TYPES as S on S.STATUS_ID = P.STATUS_ID
LEFT JOIN dbo.v_IDVAULT_ENRICHED_CURRENT_EMPLOYEES as I on I.[SID] = P.CONTACT_SID
但我得到这个错误:
操作数类型冲突:varchar 与 ListTableType 不兼容
知道为什么吗?此外,如果有另一种[更优雅]的方式来实现我想要做的事情,我也愿意接受建议!提前致谢!