在CTE中使用变量时,“必须声明标量变量@ ...”错误

时间:2016-10-08 01:02:03

标签: sql-server-2008 split common-table-expression table-variable

我将三列分成多个多个地址(每列有多个由“,”分隔的值)。我已经编写了下面的代码,但它引发了我的错误:

必须声明标量变量'@tblAddresses'。

我确实将所有内容都应用到'@tblAddresses'甚至临时表中,但是只要我执行整个代码就会出现错误。

DECLARE @tblAddresses TABLE
 ([EBN] INT, [Address (as text)] VARCHAR(4000), [Address (main)] VARCHAR(4000), [Side Address] VARCHAR(4000));

INSERT INTO @tblAddresses
        SELECT [EBN], [Address (as text)], [Address (main)],  [Side Address] FROM  [dbo].[ImportDestination]
    ---SELECT * INTO #ttAddresses FROM @tblAddresses -- I was trying with temp tbl as well changing @tblAddresses to #ttAddresseses in the CTE FROM clause column, but did not help 

;WITH AddressesCTE 
AS 
 ( 
 SELECT *
        ,CAST('<x>' + REPLACE(@tblAddresses,',','</x><x>') + '</x>' AS XML) AS AsXmlAddress

 FROM @tblAddresses
 )
 SELECT [EBN]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[1]','nvarchar(max)'))) AS [AddressText1]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[2]','nvarchar(max)'))) AS [AddressText2]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[3]','nvarchar(max)'))) AS [AddressText3]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[4]','nvarchar(max)'))) AS [AddressText4]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[5]','nvarchar(max)'))) AS [AddressText5]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[1]','nvarchar(max)'))) AS [AddressText6]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[7]','nvarchar(max)'))) AS [AddressMain1]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[8]','nvarchar(max)'))) AS [AddressMain2]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[9]','nvarchar(max)'))) AS [AddressMain3]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[10]','nvarchar(max)'))) AS [AddressMain4]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[11]','nvarchar(max)'))) AS [AddressMain5]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[12]','nvarchar(max)'))) AS [AddressMain6]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[13]','nvarchar(max)'))) AS [AddressMain7]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[14]','nvarchar(max)'))) AS [AddressSide1]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[15]','nvarchar(max)'))) AS [AddressSide2]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[16]','nvarchar(max)'))) AS [AddressSide3]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[17]','nvarchar(max)'))) AS [AddressSide4]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[18]','nvarchar(max)'))) AS [AddressSide5]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[19]','nvarchar(max)'))) AS [AddressSide6]
      ,LTRIM(RTRIM(AsXmlAddress.value('/x[20]','nvarchar(max)'))) AS [AddressSide7]
 FROM AddressesCTE

0 个答案:

没有答案