Cross apply on columns on SQL server. Syntax error near )

北城以北 提交于 2019-12-11 06:06:45

问题


I am trying to unpivot several columns, but I can't find the way of solving the syntax error.

It says incorrect syntax near ')'.

Here is the code:

SELECT dates, times, locations, events
FROM mytable
CROSS APPLY 
    (VALUES ('instance1', instance1),
            ('instance2', instance2),
            ('instance3', instance3),
            ('instance4', instance4)) as Items(locations, events)

Could it be because my SQL Server version does not support values properly and I need to store the values in a different table to refer them for cross apply?


回答1:


Since using VALUES like that has issues in your Azure SQL Data Warehouse, switch to UNPIVOT

SELECT dates, times, locations, events
FROM mytable t
UNPIVOT (events FOR [locations] IN ([instance1],[instance2],[instance3],[instance4])) AS unpvt;

Test here




回答2:


Pretty cool, I've never unpivoted that way. I always use the UNPIVOT command. But it does seem to work pretty well. Without knowing the structure of your mytable I don't know the problem, but I am guessing it doesn't have columns names instance1 through instance4?

Here's a self-contained working example:

select dates
      ,times
      ,locations
      ,events
from
(
    values
        ('20181225', 'noon', 'a', 'b', 'c', 'd')
       ,('20181226', 'midnight', 'e', 'f', 'g', 'h')
) mytable (dates, times, instance1, instance2, instance3, instance4)
cross apply
(
    values
        ('instance1', instance1)
       ,('instance2', instance2)
       ,('instance3', instance3)
       ,('instance4', instance4)
) as Items (locations, events);


来源:https://stackoverflow.com/questions/53714261/cross-apply-on-columns-on-sql-server-syntax-error-near

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!