Today I was searching for a way to put an "Order By" clause inside a Sub Query. I already know that Order By clause cannot be put inside a sub query or view. But I just need to put an order before I insert a value into a variable. The query was like this:
DECLARE @PivotField as varchar(8000);
SELECT @PivotField = '';
SELECT @PivotField = @PivotField + ',min(case when FieldName =''' + FieldName + ''' then FieldValue end)as ['+ PROMPT + ']'
FROM (
select system_id, fieldname,prompt from (
select distinct(FieldName),b.system_id,b.PROMPT from DOCSADM.HistoryMetadata a
inner join DOCSADM.DOCSCOLUMN b on b.COLNAME = a.FieldName
)y order by SYSTEM_ID
)x
And if it was executed, it will produce this error message:
Msg 1033, Level 15, State 1, Line 10
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
So the way to fix this is only by adding top n after the select clause.
the query should then be like this:
DECLARE @PivotField as varchar(8000)
SELECT @PivotField = ''
SELECT @PivotField = @PivotField + ',min(case when FieldName =''' + FieldName + ''' then FieldValue end)as ['+ PROMPT + ']'
FROM (
select top 100 system_id, fieldname,prompt from (
select distinct(FieldName),b.system_id,b.PROMPT from DOCSADM.HistoryMetadata a
inner join DOCSADM.DOCSCOLUMN b on b.COLNAME = a.FieldName
)y order by SYSTEM_ID
)x
and no error was found anymore, that simple... :)
0 comments:
Post a Comment