Yasserzaid’s Weblog

February 28, 2012

SQL Function to Convert Number to Character

Filed under: SQL Server — yasserzaid @ 8:59 pm

Hi all,

try this example to use SQL Function to Convert Number to Character


--create the following function
CREATE FUNCTION dbo.Convert_Num_ToWords
(
 @Number Numeric (38, 0) -- Input number with as many as 18 digits

) RETURNS VARCHAR(8000)
/*
* Converts a integer number as large as 34 digits into the
* equivalent words. The first letter is capitalized.
*
* Attribution: Based on NumberToWords by Srinivas Sampath
* as revised by Nick Barclay
*
* Example:
select dbo.udf_Num_ToWords (1234567890) + CHAR(10)
 + dbo.udf_Num_ToWords (0) + CHAR(10)
 + dbo.udf_Num_ToWords (123) + CHAR(10)
select dbo.udf_Num_ToWords(76543210987654321098765432109876543210)

DECLARE @i numeric (38,0)
SET @i = 0
WHILE @I <= 1000 BEGIN
 PRINT convert (char(5), @i)
 + convert(varchar(255), dbo.udf_Num_ToWords(@i))
 SET @I = @i + 1
END
*
* Published as the T-SQL UDF of the Week Vol 2 #9 2/17/03
****************************************************************/
AS BEGIN

DECLARE @inputNumber VARCHAR(38)
DECLARE @NumbersTable TABLE (number CHAR(2), word VARCHAR(10))
DECLARE @outputString VARCHAR(8000)
DECLARE @length INT
DECLARE @counter INT
DECLARE @loops INT
DECLARE @position INT
DECLARE @chunk CHAR(3) -- for chunks of 3 numbers
DECLARE @tensones CHAR(2)
DECLARE @hundreds CHAR(1)
DECLARE @tens CHAR(1)
DECLARE @ones CHAR(1)

IF @Number = 0 Return 'Zero'

-- initialize the variables
SELECT @inputNumber = CONVERT(varchar(38), @Number)
 , @outputString = ''
 , @counter = 1
SELECT @length = LEN(@inputNumber)
 , @position = LEN(@inputNumber) - 2
 , @loops = LEN(@inputNumber)/3

-- make sure there is an extra loop added for the remaining numbers
IF LEN(@inputNumber) % 3 <> 0 SET @loops = @loops + 1

-- insert data for the numbers and words
INSERT INTO @NumbersTable SELECT '00', ''
 UNION ALL SELECT '01', 'one' UNION ALL SELECT '02', 'two'
 UNION ALL SELECT '03', 'three' UNION ALL SELECT '04', 'four'
 UNION ALL SELECT '05', 'five' UNION ALL SELECT '06', 'six'
 UNION ALL SELECT '07', 'seven' UNION ALL SELECT '08', 'eight'
 UNION ALL SELECT '09', 'nine' UNION ALL SELECT '10', 'ten'
 UNION ALL SELECT '11', 'eleven' UNION ALL SELECT '12', 'twelve'
 UNION ALL SELECT '13', 'thirteen' UNION ALL SELECT '14', 'fourteen'
 UNION ALL SELECT '15', 'fifteen' UNION ALL SELECT '16', 'sixteen'
 UNION ALL SELECT '17', 'seventeen' UNION ALL SELECT '18', 'eighteen'
 UNION ALL SELECT '19', 'nineteen' UNION ALL SELECT '20', 'twenty'
 UNION ALL SELECT '30', 'thirty' UNION ALL SELECT '40', 'forty'
 UNION ALL SELECT '50', 'fifty' UNION ALL SELECT '60', 'sixty'
 UNION ALL SELECT '70', 'seventy' UNION ALL SELECT '80', 'eighty'
 UNION ALL SELECT '90', 'ninety'

WHILE @counter <= @loops BEGIN

 -- get chunks of 3 numbers at a time, padded with leading zeros
 SET @chunk = RIGHT('000' + SUBSTRING(@inputNumber, @position, 3), 3)

 IF @chunk <> '000' BEGIN
 SELECT @tensones = SUBSTRING(@chunk, 2, 2)
 , @hundreds = SUBSTRING(@chunk, 1, 1)
 , @tens = SUBSTRING(@chunk, 2, 1)
 , @ones = SUBSTRING(@chunk, 3, 1)

 -- If twenty or less, use the word directly from @NumbersTable
 IF CONVERT(INT, @tensones) <= 20 OR @Ones='0' BEGIN
 SET @outputString = (SELECT word
 FROM @NumbersTable
 WHERE @tensones = number)
 + CASE @counter WHEN 1 THEN '' -- No name
 WHEN 2 THEN ' thousand ' WHEN 3 THEN ' thousand '
 WHEN 4 THEN ' billion ' WHEN 5 THEN ' trillion '
 WHEN 6 THEN ' quadrillion ' WHEN 7 THEN ' quintillion '
 WHEN 8 THEN ' sextillion ' WHEN 9 THEN ' septillion '
 WHEN 10 THEN ' octillion ' WHEN 11 THEN ' nonillion '
 WHEN 12 THEN ' decillion ' WHEN 13 THEN ' undecillion '
 ELSE '' END
 + @outputString
 END
 ELSE BEGIN -- break down the ones and the tens separately

 SET @outputString = ' '
 + (SELECT word
 FROM @NumbersTable
 WHERE @tens + '0' = number)
 + '-'
 + (SELECT word
 FROM @NumbersTable
 WHERE '0'+ @ones = number)
 + CASE @counter WHEN 1 THEN '' -- No name
 WHEN 2 THEN ' thousand ' WHEN 3 THEN ' million '
 WHEN 4 THEN ' billion ' WHEN 5 THEN ' trillion '
 WHEN 6 THEN ' quadrillion ' WHEN 7 THEN ' quintillion '
 WHEN 8 THEN ' sextillion ' WHEN 9 THEN ' septillion '
 WHEN 10 THEN ' octillion ' WHEN 11 THEN ' nonillion '
 WHEN 12 THEN ' decillion ' WHEN 13 THEN ' undecillion '
 ELSE '' END
 + @outputString
 END

 -- now get the hundreds
 IF @hundreds <> '0' BEGIN
 SET @outputString = (SELECT word FROM @NumbersTable WHERE '0' + @hundreds = number) + ' hundred ' + @outputString
 END
 END

 SELECT @counter = @counter + 1
 , @position = @position - 3

END

-- Remove any double spaces
SET @outputString = LTRIM(RTRIM(REPLACE(@outputString, ' ', ' ')))
SET @outputstring = UPPER(LEFT(@outputstring, 1)) + SUBSTRING(@outputstring, 2, 8000)

RETURN @outputString -- return the result
END

Now to use this Function

select dbo.Convert_Num_ToWords(5800000)

Hope this helps

Good Luck

October 2, 2011

Solve Database Backup Problem

Filed under: SQL Server — yasserzaid @ 9:46 am

Hi all,

In this post i will show how to solve the error when try to backup database

Error Message :- System.Data.SqlClient.SqlError: The backup set holds a backup of a database other than the existing ‘dbName’ database. (Microsoft.SqlServer.Smo) The error Message below : Restore failed for Server ‘SQL Server name’. (Microsoft.SqlServer.Smo)

So to solve the problem, you can use the overwrite the existing database option while you’re restoring.

1) On Restore Database, select Options tab on the left menu. Then, check Overwrite the existing database on Restore options.
Note: This option will overwrite any existing data on the targeted database.

2) Try to restore the database, the problem should be gone now.
Note: you can also delete the targeted database before perform restore a database. This way also gives the result as same as the solution above.

Hope this helps

Good Luck

April 13, 2011

Convert DateTime to Different Date Format in SQL Server

Filed under: SQL Server — yasserzaid @ 11:22 am

Hi all,

try this example to Convert DateTime to Different Date Format in SQL Server like dd/MM/yyyy , MM/dd/yyyy,…etc

Open SQL Server and Open a new SQL Query :-


DECLARE @DateTime DATETIME
SELECT @DateTime =getdate()

/*For mm/dd/yyyy format*/
Select CONVERT(VARCHAR(10),@DateTime ,101) as Date

/*For yyyy.mm.dd format*/
Select CONVERT(VARCHAR(10),@DateTime ,102) as Date

/*For dd/mm/yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,103) AS Date

/*For dd.mm.yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,104) AS Date

/*For dd-mm-yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,105) AS Date

/*For hh:mi:ss format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,108) AS Date

/*For mm-dd-yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,110) AS Date

/*For yyyy/mm/dd format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,111) AS Date

/*For yyyymmdd format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,112) AS Date

Hope this helps

Good Luck

April 7, 2011

Calculate Age in Day-Month-Year using SQL Server Query

Filed under: SQL Server — yasserzaid @ 1:32 pm

Hi all,

try this example to create SQL Server Stored Procdure to Calculate  Age in Day-Month-Year

create proc CalculateAge
(
@dayOfBirth datetime
)
as
begin
DECLARE @today datetime, @thisYearBirthDay datetime
DECLARE @years int, @months int, @days int 
SELECT @today = GETDATE() 
SELECT @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth) 
SELECT @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END) 
SELECT @months = MONTH(@today - @thisYearBirthDay) - 1 
SELECT @days = DAY(@today - @thisYearBirthDay) - 1 
SELECT @years as years, @months as months, @days as days
end

and to use this Stored Procedure

exec CalculateAge '01/21/1984'

Hope this helps

Good Luck

March 24, 2011

Get Difference between two Dates using SQL Server

Filed under: SQL Server — yasserzaid @ 1:15 pm

Hi all,

try this example to Create Stored Procedure to Get Difference between two Dates in Years , Months and Days

So try this SQL Query to Create Stored Procedure which Take two Parameters (FromDate and ToDate)

create proc CalculateDifference
(
@FromDate datetime,
@ToDate datetime
)
as
begin 
DECLARE @thisYear datetime
DECLARE @years int, @months int, @days int  
SELECT @thisYear = DATEADD(year, DATEDIFF(year, @FromDate, @ToDate), @FromDate) 
SELECT @years = DATEDIFF(year, @FromDate, @ToDate) - (CASE WHEN @thisYear > @ToDate THEN 1 ELSE 0 END) 
SELECT @months = MONTH(@ToDate - @thisYear) - 1 
SELECT @days = DAY(@ToDate - @thisYear) - 1 
SELECT @years as years, @months as months, @days as days
end

and To execute this Stored Procedure write this Query

exec CalculateDifference '01/21/1984','03/24/2011'

Hope this helps,

Good Luck

March 21, 2011

Get Last Day of Any Month (Current and Previous and Next)

Filed under: SQL Server — yasserzaid @ 8:43 am

Hi all

try this example to Get Last Day of Any Month (Current and Previous and Next)

Open SQL Server and write this Query :-

----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth

If you want to find last day of month of any day specified use this Query :-

--Last Day of Any Month and Year
DECLARE @dtDate DATETIME
SET @dtDate = '8/18/2011'
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
LastDay_AnyMonth

Hope this helps

Good Luck

March 20, 2011

Convert Hijri Data To Gregorian And Reversal

Filed under: SQL Server — yasserzaid @ 10:33 am

Hi all,

try this Example to Convert Hijri Data To Gregorian And Reversal using MS SQL Server

** To Convert Hijri Data To Gregorian  we can write this query which will do that :-

select convert(datetime,'22/02/1432',131)

** To Convert from Gregorian Date to Hijri date we can write is sql query :-

select convert(nvarchar(15),getdate(),131)

Hope this helps

GoodLuck

February 3, 2011

SQL Server Function to Split Comma in Text

Filed under: SQL Server — yasserzaid @ 4:41 pm

Hi all

try this example to use SQL Server Function to Split Comma in Text

so Open SQL Server Management Studio and create a new SQL Query


create FUNCTION [dbo].[Fn_Split]
(
 @RowData nvarchar(max),
 @SplitOn nvarchar(5)
) 
RETURNS @RtnValue table
(
 Id int identity(1,1),
 Data nvarchar(100)
)
AS 
BEGIN
 Declare @Cnt int
 Set @Cnt = 1

 While (Charindex(@SplitOn,@RowData)>0)
 Begin
  Insert Into @RtnValue (data)
  Select Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
  Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
  Set @Cnt = @Cnt + 1
 End
 Insert Into @RtnValue (data)
 Select Data = ltrim(rtrim(@RowData))
 Return
END

and to use this function

select * from  dbo.Fn_Split ('Item 1,Item 2,Item 3,Item 4,Item 5,Item 6' )

Hope this helps

Good Luck

December 24, 2010

Get All Tables Name of Database

Filed under: SQL Server — yasserzaid @ 3:53 pm

Hi all,

try this example using SQL Server Query to Get all Tables name of Spacififc Database

so Open MS SQL Server and write this Query :-

In this example i will get all tables name of Northwind Database

USE NORTHWIND
SELECT * FROM information_schema.tables ORDER BY table_TYPE

Hope this helps

Good Luck

October 9, 2010

Select Multiple Rows in One Row SQL Server

Filed under: SQL Server — yasserzaid @ 6:51 pm

Hi all,

try this example to combine multiple rows into one


declare @Table Table
(
[Numbers] varchar(40)
)
INSERT INTO @Table VALUES('One');
INSERT INTO @Table VALUES('Two');
INSERT INTO @Table VALUES('Three');
INSERT INTO @Table VALUES('Four');
INSERT INTO @Table VALUES('Five');

-- Query to combine multiple rows into one
DECLARE @str VARCHAR(100)
SELECT @str = COALESCE(@str + '|', '') + [Numbers]
FROM @Table
Print @str

Hope this helps

Good Luck

Older Posts »

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.