语法错误但不确定原因(SQL Server)

时间:2014-03-02 13:39:21

标签: sql sql-server database

INSERT into LibraryTable(ID, Artist, Name, Rating, PlayCount) VALUES(
Select MIN(a.ID + 1)
From LibraryTable A
Left Join LibraryTable B
On A.ID = B.ID - 1
Where B.ID Is NULL, 'eg', 'eg', 1, 1)

我在“选择”时收到语法错误,在“空”后收到“,”。我是一个初学者,所以任何有用的提示将不胜感激。

3 个答案:

答案 0 :(得分:3)

您想要insert . . . select

INSERT into LibraryTable(ID, Artist, Name, Rating, PlayCount)
    Select MIN(a.ID + 1), 'eq', 'eq', 1, 1
    From LibraryTable A Left Join
         LibraryTable B
         On A.ID = B.ID - 1
    Where B.ID Is NULL;

values

这种形式不使用insert关键字。

如果您使用的是SQL Server 2012,则可以使用lead()函数而不是自联接来执行此操作:

INSERT into LibraryTable(ID, Artist, Name, Rating, PlayCount)
    Select MIN(lt.ID + 1), 'eq', 'eq', 1, 1
    From (select lt.*, lead(id, 1) over (order by id) as nextid
          from LibraryTable lt
         ) lt Left Join
    where nextid <> id + 1;

答案 1 :(得分:0)

尝试这个:

INSERT into LibraryTable(ID, Artist, Name, Rating, PlayCount) 
Select MIN(a.ID + 1) as ID, 'eg' as Artist, 'eg' as Name, 1 as Rating, 1 as PlayCount
From LibraryTable A
Left Join LibraryTable B
On A.ID = B.ID - 1
Where B.ID Is NULL

答案 2 :(得分:0)

您正在尝试插入一个值,但语法需要五个。尝试...

INSERT  INTO LibraryTable
        ( ID ,
          Artist ,
          Name ,
          Rating ,
          PlayCount
        )
        SELECT  MIN(a.ID + 1) AS ID ,
                'eg' ,
                'eg' ,
                1 ,
                1
        FROM    LibraryTable A
                LEFT JOIN LibraryTable B ON A.ID = B.ID - 1
        WHERE   B.ID IS NULL

article here解释。