INNER JOIN 的结果和同时连接的两个表的别名

Alias for the results of the INNER JOIN and for both tables that are being joined at the same time

USE [MasterDB]

GO
CREATE proc  dbo.ProductPropertiesInsert
AS
SET NOCOUNT ON;

INSERT INTO [MasterDB].[Main].[Property]
SELECT vp.Product_ID, vp.Property_ID
FROM ( SELECT * FROM [MasterDB].[Product].[Report] vr INNER JOIN [MasterDB].[Main].[Product] jt ON vr.vin=v.VIN )
     cross apply (values (208, jt.id, jt.IsExclusive), 
                         (209, jt.id, jt.IsNew),
                         (213, jt.id, jt.IsPremium)) 
                         vp(Property_ID, Product_ID, property)
WHERE vp.property=1
      /* optional code? */
      and not exists(select 1 
                     from [HGregoireCentral].[Main].[Property] p_in
                     where vp.id=p_in.id
                           and vp.Property_ID=p.Property_ID);
GO

我有这个存储过程,但我想知道 jt 的别名是内部连接的别名还是 [MasterDB].[Main].[Product].

的别名

我在vr.vin=v.VIN加入它,v代表[MasterDB].[Main].[Product],但是因为v没有定义,我需要内连接对于交叉应用语句,我不确定如何正确执行。截至目前,我认为该语句不起作用,因为我需要一个别名作为内部连接的结果和 table [MasterDB].[Main].[Product].

你是怎么做到的?

举报Table

vin isNew isExclusive isPremium 
11   1       1          0  
12   0       0          1 
13   1       0          1 

Main Table(用于获取 属性 table 的 属性 id)

vin id 
11  10 
12  11 
13  12 

属性 Table(我需要为每个 属性Id 从第一个 table 插入行)

id propertyId 
10 1 
10 2 
11 3 
12 1 
12 3

我不确定您的查询是否有效SQL服务器代码:

  • from子句中的子查询不是别名

  • jt在子查询中定义,不应该在外部查询中可用。

但基本上,我认为您根本不需要那个子查询。您可以将联接展平,例如:

INSERT INTO [MasterDB].[Main].[Property]
SELECT vp.Product_ID, vp.Property_ID
FROM [MasterDB].[Product].[Report] vr 
INNER JOIN [MasterDB].[Main].[Product] jt ON jt.vin = vr.VIN
CROSS APPLY (VALUES 
    (208, jt.id, jt.IsExclusive), 
    (209, jt.id, jt.IsNew),
    (213, jt.id, jt.IsPremium)
) vp(Property_ID, Product_ID, property)
WHERE 
    vp.property=1
    AND NOT EXISTS (
        SELECT 1 
        FROM [HGregoireCentral].[Main].[Property] p_in
        WHERE vp.id = p_in.id AND vp.Property_ID = p_in.Property_ID
    )

请注意,我还修复了 NOT EXISTS 子查询中不正确的 table 别名 p - 据推测,您的意思是 p_injoin.

中的别名 v 也是如此