简体   繁体   中英

DISTINCT and ORDER BY query not working in SQL Server 2012

We've migrated our database from MS SQL 2008 to SQL2012. After migration some of the queries does not working. Below query is working with SQL2008 and SQL2000 but does not working with SQL2012

SELECT DISTINCT Field1, Field1+ ' - ' + Field1 as Field1 FROM TABLE ORDER BY Field1

Msg 209, Level 16, State 1, Line 1 Ambiguous column name 'MCH_GROUP'.

I know we can modify the queries but we've a lot of applications. I think there should be a path or a settings to execute this query without any error on sql 2012.

The error comes due to the order by clause. Server cannot distinguish between the two Field1 columns. Please give a different name for 2nd column.

SELECT      DISTINCT Field1, 
            Field1+ ' - ' + Field1 as Field2 
FROM        TABLE 
ORDER BY    Field1

Another Eg:
SELECT      DISTINCT [FirstName], 
            [FirstName] + ' - ' + [FirstName]  As [TwiceFirstName]
FROM        [dbo].[DimCustomer]
ORDER BY    [FirstName]
SELECT DISTINCT Field1, Field1+ ' - ' + Field1 as Field2 FROM TABLE ORDER BY Field1

你把2个字段称为相同,然后你把这个命令混淆了......

尝试这个,

SELECT DISTINCT Field1, Field1+ ' - ' + Field1 as CalcualtedField FROM TABLE ORDER BY Field1

If you absolutely cannot change the queries (which you should do) then set the compatibility level for the database to SQL2000. Right click database, Properties, Options, set Compatibility level to SQL Server 2000 (80)

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