别名内部联接会导致列名无效

时间:2014-05-22 13:47:51

标签: sql-server inner-join alias

我尝试INNER JOIN三个表并让它返回XML文件的值,但是来自第二个或第三个表的值将返回为

  

Msg 207,Level 16,State 1,Procedure PROC_Generate_XML_AdForm,Line   18列名无效' VPrSKzNazev'。

     

Msg 207,Level 16,State 1,Procedure PROC_Generate_XML_AdForm,Line   20列名称无效' VPrURLCZ1'。

     

Msg 207,Level 16,State 1,Procedure PROC_Generate_XML_AdForm,Line   22列名称无效' VPrSlevaCZ1'。

以下是代码:

SELECT @xmlVar = (
    SELECT t1.IDS AS 'product_id'
        ,t1.VPrSKzNazev AS 'product_name'
        ,t1.VPrPodkolekce AS 'product_category_id'
        ,'http://www.foo.com/' + t1.VPrURLCZ1 AS 'product_deeplink'
        ,'http://www.foo.com/media-photo/' + t1.IDS + '/370/370.jpg' AS 'product_image'
        ,CAST(ROUND((100 - t1.ProdejDPH) / 100 * t1.VPrSlevaCZ1, 0) AS INT) AS 'product_price'
    FROM SKz AS t1
    INNER JOIN VTbProdDalsi
        ON t1.IDS = VTbProdDalsi.VPrSKzIDS
    INNER JOIN VTbProdDalsi2
        ON t1.IDS = VTbProdDalsi2.VPrSKzIDS
    WHERE t1.VPrIsMain = 1
        AND (
            (
                SELECT SUM(SKz.StavZ - SKz.ObjedP)
                FROM SKz
                WHERE IDS = t1.IDS
                ) > 0
            OR (
                SELECT SUM(ISNULL(SKz.VPrDodPocet, 0) - SKz.ObjedP)
                FROM SKz
                WHERE IDS = t1.IDS
                ) > 0
            )
    FOR XML PATH('product')
        ,ROOT('products')
    )

我认为它可能已经在某个地方得到了解答,但由于我是SQL的新手,我不确定如何调整答案。

我在Microsoft SQL Server Management Studio(SQL Server 2008 R2)上。

感谢您的回复。

2 个答案:

答案 0 :(得分:0)

好像你的问题就在这里:

,t1.VPrSKzNazev AS 'product_name'
        ,t1.VPrPodkolekce AS 'product_category_id'
        ,'http://www.foo.com/' + t1.VPrURLCZ1 AS 'product_deeplink'

我会确保这些名字与表格Skz中的内容相符。 另外,如果你无法弄明白,你能否给我们一份Skz的专栏列表?

答案 1 :(得分:0)

解决。

解决方案是不要将连接表t1用于不在SKz表中的变量。

    select @xmlVar =
    (
    select 
            t1.IDS as 'product_id',
      VTbProdDalsi.VPrSKzNazev as 'product_name',
      t1.VPrPodkolekce as 'product_category_id',
      'http://www.ringit.cz/' + VTbProdDalsi2.VPrURLCZ1 as 'product_deeplink',
      'http://www.ringit.cz/media-photo/' + t1.IDS + '/370/370.jpg' as 'product_image',
      CAST(ROUND(t1.ProdejDPH - t1.ProdejDPH * VTbProdDalsi.VPrSlevaCZ1/100, 0) AS int) as 'product_price'

    from SKz as t1
      inner join VTbProdDalsi on t1.IDS = VTbProdDalsi.VPrSKzIDS 
        inner join VTbProdDalsi2 on t1.IDS = VTbProdDalsi2.VPrSKzIDS
      where t1.VPrIsMain = 1 AND t1.VPrGledis = 1 AND
      ((SELECT SUM(SKz.StavZ - SKz.ObjedP) FROM SKz WHERE IDS = t1.IDS) > 0 OR (SELECT SUM(ISNULL(SKz.VPrDodPocet, 0) - SKz.ObjedP) FROM SKz WHERE IDS = t1.IDS) > 0)
  FOR XML PATH ('product'), ROOT ('products') 
  )