我有一个函数dbo.getMyTableBasedOnId(),它返回一个不同的缓存表名称,我想将它分配给一个变量,以便在具有多个JOIN的SELECT语句中使用。我不确定如何将此函数的结果设置为变量,然后使用WITH和MERGE INTO(如果这是正确的路径)而不是JOIN。我在下面的尝试不起作用。
DECLARE @MyTableName varchar(50)
SET @MyTableName = (SELECT dbo.getMyTableBasedOnId(123))
SELECT @MyTableName
SELECT i.personName, a.weight
FROM peopleTable1 i
JOIN (select [id], [weight] from @MyTableName) as a
ON a.personName = i.personName
WHERE i.City IN ('New York', 'Atlanta')
提前感谢您的帮助。
答案 0 :(得分:0)
试试这个
DECLARE @MyTableName varchar(50)
DECLARE @QUERY NVARCHAR(4000)
SET @MyTableName = (SELECT dbo.getMyTableBasedOnId(123))
SELECT @MyTableName
SET @QUERY='SELECT i.personName, a.weight
FROM peopleTable1 i
JOIN (select [id], [weight] from '+@MyTableName+') as a
ON a.personName = i.personName
WHERE i.City IN (''New York'', ''Atlanta'')'
EXEC SP_EXECUTESQL @QUERY
由于