SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to apply nested CONVERTs for complex data conversion?

The following SQL Server T-SQL sample scripts demonstrates the use of nested CONVERTs to remove special characters and convert the price result column into money data type first, then into currency format. The CONVERT function and nested CONVERTs are very fast.

-- T-SQL remove special characters from string including space by nesting converts
DECLARE @text nvarchar(128) = '#124 $99^@'
SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
       REPLACE(REPLACE(REPLACE(REPLACE(@text,
        '!',''),'@',''),'#',''),'$',''),'%',''),
        '^',''),'&',''),'*',''),' ','')

-- 12499

-- SQL Server nested CONVERTs - SQL format money as currency

-- SQL group by - sum aggregate function

USE Northwind;

 

SELECT   ProductName,

         AveragePrice = '$' + CONVERT(VARCHAR,CONVERT(MONEY,

         AVG(od.UnitPrice * (1.00 - Discount)),  1)),

         UnitsSold = SUM(od.Quantity)

FROM     dbo.[Order Details]  AS od,

         dbo.Products         AS p,

         dbo.Orders           AS o

WHERE    od.ProductID = p.ProductID

         AND o.OrderID = od.OrderID

         AND od.UnitPrice > 8.0

GROUP BY ProductName,

         od.ProductID

ORDER BY ProductName

GO

/* Partial results

 

ProductName AveragePrice      UnitsSold

Alice Mutton      $34.23      978

Aniseed Syrup     $9.89 228

Boston Crab Meat  $16.35      1103

Camembert Pierrot $30.12      1577

Carnarvon Tigers  $54.91      539

Chai  $15.80      828

*/

Related article:

Datetime Conversion

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.