我在SQL Server 2012中收到以下错误:
无效的对象名称“Libraries”。
有没有办法修改语法,所以我不必使用表变量?问题出现在我放置into语句的代码的末尾。
以下是代码:
SET NOCOUNT ON
declare @level int = 0
DECLARE @DataLibraryName VARCHAR(500)
SET @DataLibraryName = 'FN_PerfSalesChargeFeeReplacementText';
IF LTRIM(RTRIM(@DataLibraryName)) = ''
SET @DataLibraryName = null;
WITH DataLibraryRaw AS
(
SELECT
*
,CAST(CAST(dataLibraryXML AS NTEXT) AS XML) dataLibraryXMLData
,datasource_name dataLibraryName
FROM
tblrpt_datascript
--WHERE datasource_type = 'DLMERGE'
),
DataLibraryDep AS
(
SELECT
dataLibraryName
,dataLibraryXMLData.query('//SourceSpecification') [SourceSpecification]
FROM
DataLibraryRaw
),
DependenciesXML AS
(
SELECT
dataLibraryName
,CAST(REPLACE(REPLACE(CAST([SourceSpecification] AS NVARCHAR(MAX)), '#', '<item>#'), '}', '}</item>') AS XML) AS dataLibraryXMLData
FROM
DataLibraryDep
),
DataLibraries AS
(
SELECT
dataLibraryName
,d.i.query('.').value('.', 'nvarchar(max)') dependDataLibrary
FROM
DependenciesXML dx
CROSS APPLY
dataLibraryXMLData.nodes('//item') AS d(i)
),
Libraries AS
(
SELECT
dataLibraryName parentDL
,LTRIM(RTRIM(SUBSTRING([dependDataLibrary], CHARINDEX('=', [dependDataLibrary] ,1)+1 ,CHARINDEX('{', [dependDataLibrary], 1)-(CHARINDEX('=', [dependDataLibrary] ,1)+1)))) childDL
FROM
DataLibraries
),
RecursiveData AS
(
SELECT
*, 0 AS LEVEL
FROM
Libraries
WHERE
parentDL = IsNull(@DataLibraryName, parentDL)
)
SELECT *
FROM RecursiveData
---- Recursive member definition
insert RecursiveData
SELECT
m.parentDL, m.childDL,
@level + 1
FROM
Libraries m
INNER JOIN
RecursiveData r ON r.childDL = m.parentDL AND r.level = @level
提前谢谢你。
答案 0 :(得分:0)
根据您上面的脚本,问题是您正在从CTE中进行选择:
SELECT * FROM RecursiveData
然后做插入:
insert RecursiveData
SELECT m.parentDL, m.childDL,
@level + 1
FROM Libraries m
INNER JOIN RecursiveData r
ON r.childDL = m.parentDL and r.level = @level
在使用CTE之后,您无法引用CTE,因此只要SELECT *
语句存在,您的插入就会失败。然而,另一个问题是你似乎试图插入你的最后一个CTE,RecursiveData,它也不会像你期望的那样工作。
在插入之前,您的代码的最后一部分应该是:
,RecursiveData AS (
SELECT ParentDL, ChildDL, 0 AS LEVEL
FROM Libraries
WHERE parentDL = IsNull(@DataLibraryName, parentDL)
UNION ALL
SELECT l.PARENTDL, l.CHILDDL, r.LEVEL + 1
FROM Libraries l
JOIN RecursiveData r ON r.CHILDDL = l.PARENTDL
)
SELECT * FROM RecursiveData
并且您想要完全关闭插件(或将其插入您需要的任何表格中)。