使用表变量中的列时“无效列”

时间:2013-10-30 01:38:39

标签: sql join

我正在尝试声明一个表变量,然后将它连接到我在数据库中创建的表。每当我尝试将“NAME”字段插入表格时,即使GNAME字段正常,我也会收到错误“Invalid Column Name "NAME"”。我做错了什么,我怎样才能加入NAME栏目?

DECLARE @Names TABLE
(
    ID INT,
    NAME VARCHAR(100),
    GNAME VARCHAR(100)
)

INSERT INTO @Names
(
    ID,
    NAME,
    GNAME
)

SELECT
    CName.ID,
    Ref.NAME,
    Ref.GNAME
FROM
    @CurrentPositions AS CName
LEFT OUTER JOIN
    dbo.NameField AS Ref
ON 
    CName.ID = Ref.ID

    IF ( OBJECT_ID('dbo.ReportTable', 'U') IS NOT NULL)
    DROP TABLE dbo.ReportTable

CREATE TABLE [dbo].[ReportTable]
(
    [ID_NUMBER] [INT],
    [NAME] [VARCHAR](150)
    [GNAME] [VARCHAR](150)
)

INSERT INTO [dbo].[ReportTable]
(
    ID_NUMBER,
    NAME,
    GNAME
)

SELECT
    C.ID_NUMBER,
    N.NAME,
    N.GNAME
FROM
    @Names AS N
INNER JOIN
    @CurrentPositions AS C
ON  N.ID_NUMBER = C.ID_NUMBER

2 个答案:

答案 0 :(得分:1)

尝试使用临时表

CREATE TABLE #Names 
(
    ID INT,
    NAME VARCHAR(100),
    GNAME VARCHAR(100)
)

INSERT INTO #Names
(
    ID,
    NAME,
    GNAME
)
SELECT
    CName.ID,
    Ref.NAME,
    Ref.GNAME
FROM
    #CurrentPositions AS CName
LEFT OUTER JOIN
    dbo.NameField AS Ref
ON 
    CName.ID = Ref.ID

    IF ( OBJECT_ID('dbo.ReportTable', 'U') IS NOT NULL)
    DROP TABLE dbo.ReportTable

CREATE TABLE [dbo].[ReportTable]
(
    [ID_NUMBER] [INT],
    [NAME] [VARCHAR](150)
    [GNAME] [VARCHAR](150)
)

INSERT INTO [dbo].[ReportTable]
(
    ID_NUMBER,
    NAME,
    GNAME
)

SELECT
    C.ID_NUMBER,
    N.NAME,
    N.GNAME
FROM
    #Names AS N
INNER JOIN
    #CurrentPositions AS C
ON  N.ID_NUMBER = C.ID_NUMBER

我假设您还将表变量@CurrentPositions更改为临时表

请记住在使用它们之后删除它们。

答案 1 :(得分:0)

您可能需要做的就是将字段名称包装在方括号中,例如

INSERT INTO @Names
(
    [ID],
    [NAME],
    [GNAME]
)

SELECT
    CName.[ID],
    Ref.[NAME],
    Ref.[GNAME]
FROM
    @CurrentPositions AS CName
LEFT OUTER JOIN
    dbo.NameField AS Ref
ON 
    CName.[ID] = Ref.[ID]

如果仍无法解决问题,请发布@CurrentPositionsdbo.NameField表的架构。