简体   繁体   中英

Incorrect syntax near the keyword 'FOR'

I have written the query mentioned below...

    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name)  
                    from dbo.[WorkflowInstanceParameter] 
            FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')


Go 
set @query = 'SELECT ' + @cols + ' 
            from 
            (
                select wi.Id,wip.Name, wip.stringValue
                from FROM [ESP2_DEV1].[dbo].[WorkflowInstanceParameter] wip,
 [WorkflowParameterGroupInstance] wpgi, [ESP2_DEV1].[dbo].[WorkflowInstance] wi,
 dbo.WorkflowDefinition wd
 where wip.[WorkflowParameterGroupInstanceId] = wpgi.id
 and wpgi.[WorkflowInstanceId] =wi.id and
  wi.workflowDefinitionId=wd.id
            ) x
            pivot 
            (
                max(stringValue)
                for Name in (' + @cols + ')
            ) p '

execute(@query)

but it is failing with error "Incorrect syntax near the keyword 'FOR'"

Can anyone help me this?????

This isn't really an answer for this post but if you google this error its one of the top hits.

I was running into this problem because I was trying to name a cursor with @

declare @someName cursor for 

this doesnt work.

You need to do:

declare someName cursor for 

instead.

I'm not clear if this is always the case as I've seen plenty of examples online which use @ and plenty which dont which is confusing. I'm new to sqlserver so not sure if there is something subtle going on here. However this definitely fixed the error in my case. This point seems to not be documented much online, however this other question documents it but was much harder to find on google for some reason!

Funny thing to force on names! I'm convertinig an oracle schema to sqlserver and had to add @ to variables everywhere but not these ones apparently! I guess the guys who did cursors missed that meeting or something!

The keyword FROM is repeated in the set @query clause:

select wi.Id,wip.Name, wip.stringValue
            from FROM [ESP2_DEV1].[dbo].[WorkflowInstanceParameter] wip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM