Category Archives: SQL Server

Home / SQL Server
48 Posts

I have a query for which the keys must appear distinctly, but they are duplicated in the resultset. I want to keep only one of the duplicated rows. That is, if I find a record with a duplicated key, I want to keep only one of the records and all of its other data. I don’t care which of the rows get dumped. Admittedly, this is a strange and rare situation (all the more reason to document it).

Deleting all but one duplicated row

Adapted from “Unique Indexes Are Code; Non-Unique Indexes Are Data” By Daniel White, 2014/06/26

In any Excel cell that needs line-breaks, instead of using ALT-ENTER, put a placeholder {NL} in the Excel cell’s text.

Example: 123 Maple St{NL}Apt 2{NL}Sacramento,CA{NL}95818

Paste the Excel data into the SQL table as normal.

Execute this SQL statement to change the placeholders to SQL line-break characters:

update [tablename] set [fieldname] = replace([fieldname],'{NL}',CHAR(13))

Generates a unique namespace that conforms to DNS name format from the input.

Releated: Validate Format of a Domain Name post

Input formats:
If email address, the host part is used.
If URI, the primary domain name is used.
If neither of the above formats then uses the input as is.
Looks in the [Subscription] table of the specified database table for the [Namespace] column to determine uniqueness.

 

Using setvar in T-SQL

This example changes the value of the [Namespace] field for all records of all tables where the column is found.