0

我正在尝试声明一个表变量,然后将其加入到我在数据库中创建的表中。每次我尝试将我的“ NAME”字段插入到我的表中时,我都会收到错误“ Invalid Column Name "NAME"”,即使 GNAME 字段工作正常。我做错了什么,我该如何加入我的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
4

2 回答 2

1

尝试使用Temp 表

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为临时表

请记住在使用它们后放下表格。

于 2013-10-30T01:54:19.067 回答
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表的架构。

于 2013-10-30T02:54:28.947 回答