Skip to content

Commit 89211bf

Browse files
committed
Fix ORDER BY items must appear in the select list if SELECT DISTINCT
Please see #306 for more details.
1 parent 0339e8e commit 89211bf

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

lib/active_record/connection_adapters/sqlserver/schema_statements.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,15 @@ def type_to_sql(type, limit = nil, precision = nil, scale = nil)
131131
end
132132
end
133133

134+
def columns_for_distinct(columns, orders)
135+
order_columns = orders.reject(&:blank?).map{ |s|
136+
s = s.to_sql unless s.is_a?(String)
137+
s.gsub(/\s+(?:ASC|DESC)\b/i, '')
138+
.gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, '')
139+
}.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" }
140+
[super, *order_columns].join(', ')
141+
end
142+
134143
def change_column_null(table_name, column_name, allow_null, default = nil)
135144
column = detect_column_for! table_name, column_name
136145
if !allow_null.nil? && allow_null == false && !default.nil?

0 commit comments

Comments
 (0)