Question

So let's say 'table' has two columns that act as a GUID - the ID column and msrepl_tran_version. Our original programmer did not know that our replication created this column and included it in a comparison, which has resulted in almost 20,000 records being put into this table, of which only 1,588 are ACTUALLY unique, and it's causing long load times.

I'm looking for a way to exclude the ID and replication columns from a select distinct, without having to then list every single column in the table, since I'm going to have to select from the record set multiple times to fix this (there are other tables affected and the query is going to be ridiculous) I don't want to have to deal with my code being messy if I can help it.

Is there a way to accomplish this without listing all of the other columns?

Select distinct {* except ID, msrepl_tran_version} from table

Other than (where COL_1 is ID and COL_N is the replication GUID)

Select distinct COL_2, ..., COL_N-1, COL_N+1, ... from table
Était-ce utile?

La solution

After more searching, I found the answer:

SELECT * INTO #temp FROM table
ALTER TABLE #temp DROP COLUMN id
ALTER TABLE #temp DROP COLUMN msrepl_tran_version
SELECT DISTINCT * FROM #temp

This works for what I need. Thanks for the answers guys!

Autres conseils

Absolutely, 100% not possible, there is no subtract columns instruction.

It can't be done in the spirit of the OP's initial question. However, it can be done with dynamic sql:

--Dynamically build list of column names.
DECLARE @ColNames NVARCHAR(MAX) = ''

SELECT @ColNames = @ColNames + '[' + c.COLUMN_NAME + '],'
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_SCHEMA = 'dbo'
AND c.TABLE_NAME = 'YourTable'
--Exclude these.
AND c.COLUMN_NAME NOT IN ('ID', 'msrepl_tran_version')
--Keep original column order for appearance, convenience.
ORDER BY c.ORDINAL_POSITION

--Remove trailing comma.
SET @ColNames = LEFT(@ColNames, LEN(@ColNames) - 1)

--Verify query
PRINT ('SELECT DISTINCT ' + @ColNames + ' FROM [dbo].[YourTable]')

--Uncomment when ready to proceed.
--EXEC ('SELECT DISTINCT ' + @ColNames + ' FROM [dbo].[YourTable]')

One additional note: since you need to select from the record set multiple times and potentially join to other tables, you can use the above to create a view on the table. This should make your code fairly clean.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top