为什么@Table不适合我?

时间:2010-07-28 10:52:55

标签: sql-server-2008

有人能说出为什么这个查询不起作用吗?

DECLARE @unwantedRows TABLE 
( 
    ProductId INT, 
    ProductName VARCHAR(50),
    Description VARCHAR(50),
    Category VARCHAR(50),
    Repetitions VARCHAR(50)

);

Select *
INTO @unwantedRows From
(
Select a.*,Row_Number() Over(Partition By ProductId Order By ProductId)  As [Repetitons]  from tblProduct a
) As A

Where A.Repetitons > 1

我得到的错误是

`Msg 102,Level 15,State 1,Line 12 '@unwantedRows'附近的语法不正确。 消息156,第15级,状态1,第15行 关键字“As”附近的语法不正确。

修改:

现在它正在给Repetitions: -

INSERT
INTO @unwantedRows 
Select a.*,Row_Number() Over(Partition By ProductId Order By ProductId)  As [Repetitons]  from tblProduct a
Where a.Repetitons > 1

`

Invalid column name 'Repetitons'.

4 个答案:

答案 0 :(得分:1)

因为select into创建了一个表,并且您想要insert into @unwantedRows select * from ...


修改

然后,您不能在Where子句中使用窗口函数(例如Partition)。如果必须这样做,请将您的选择包装到另一个选择中:

select * from (select * from ...) as a where a.Partition > 1

答案 1 :(得分:1)

我发现的一个错误是选择选择..插入语句

以下查询正常工作没有错误,即语法错误

DECLARE @unwantedRows TABLE 
( 
    ProductId INT, 
    ProductName VARCHAR(50),
    Description VARCHAR(50),
    Category VARCHAR(50),
    Repetitions VARCHAR(50)

);

insert INTO @unwantedRows 
Select a.*,Row_Number() Over(Partition By ProductId Order By ProductId)  As [Repetitons]  from tblProduct 
Where A.Repetitons > 1

不受上述查询的影响,您也可以尝试这个

insert INTO @unwantedRows 
select * from (
Select a.*,Row_Number() Over(Partition By ProductId Order By ProductId)  As [Repetitons]  from tblProduct ) d
Where d.Repetitons > 1

答案 2 :(得分:1)

您需要删除SELECT INTO,并且需要指定列。

INSERT @unwantedRows 
SELECT a.ProductID, a.ProductName, a.Description, a.Category, a.Repetitions
FROM (
    Select *, Row_Number() Over (Partition By ProductId Order By ProductId) As [Repetitons]  
    from tblProduct) As A
Where A.Repetitons > 1;

答案 3 :(得分:0)

insert into @unwantedRows 
Select * from
(
Select a.*,Row_Number() Over(Partition By ProductId Order By ProductId)  As [Repetitons]  from tblProduct a
) As A
Where A.Repetitons > 1