Skip to content
Advertisement

Keep ORDER BY clause is invalid in view

I have the following SQL Statement:

Select CountryCodeTwoChar
FROM (Select CountryCodeTwoChar From [Country] Order By CountryName ) TBL
Where CountryCodeTwoChar = N'PS'

But I have the following Error from SQL Server:

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.

I know it gave the error for the Statement:

Select CountryCodeTwoChar From [Country] Order By CountryName

But that is auto-generated by the system so I cannot change it!

How to re-write the statement keeping the statement there (Select CountryCodeTwoChar From [Country] Order By CountryName)?

{Edit}

I Tried the following, is that good?

declare @userData TABLE(
                    CountryCodeTwoChar varchar(30) NOT NULL
                   )
Insert into @userData
Select CountryCodeTwoChar From [Country] Order By CountryName

Select CountryCodeTwoChar FROM @userData Where CountryCodeTwoChar = N'PS'

Advertisement

Answer

How to re-write the statement keeping the statement there (Select CountryCodeTwoChar From [Country] Order By CountryName)?

This will not be possible. There is NO WAY you can use that exact statement in a derived table. If you can’t change it, you’re out of luck.

If you are able to write multiple statements for a solution, so long as you use the exact statement above, then you can use that statement to populate a table variable, and then select from the table variable with your WHERE clause.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement