Wednesday, July 28, 2010

Error when exporting data to Excel

While exporting data from SQL Server 2005 to Excel, I got an error "Columns "Field1" and "F1" cannot convert between unicode and non-unicode string data types". I was exporting data returned by a particular view. In order to fix the issue I had to modify the view, utilizing CAST function to cast the columns to their existing data type. Weird, huh?

Here is my original view. Please note that Field1 and Field2 are of type varchar(5) and varchar(100) respectively:


CREATE VIEW [dbo].[myView]
AS
SELECT Field1,
Field2
FROM Table1


Here is what I modified my view to and what worked for me:


CREATE VIEW [dbo].[myView]
AS
SELECT CAST(Field1 As Varchar(50)) as Field1,
CAST (Field2 as Varchar(100)) As Field2
FROM Table1

Monday, July 26, 2010

How to delete duplicate records from SQL Server table

This can be done in 4 simple steps, utilizing temp tables.

First you need to identify duplicate records and insert them into a temp table:


INSERT INTO #mytemptbl
SELECT * FROM Table1
GROUP BY field1, field2, field3
Having COUNT(*) > 1


Then delete those records from the original table:


DELETE FROM Table1
FROM Table1
INNER JOIN #mytemptbl
ON Table1.field1 = #mytemptbl.field1
AND Table1.field2 = #mytemptbl.field2
AND Table1.field3 = #mytemptbl.field3


Next re-insert records from temp table into the original table:


INSERT INTO Table1
SELECT * FROM #mytemptbl



And finally drop temp table:


DROP TABLE #mytemptbl