Monday, March 19, 2012

hhmmss Time format in SQL Server - How?

Hi !!

I am having difficulties working with SQL Server SmallDataTime...

I use TransactionDate as smalldatetime.. Now for reporting purpose my client needs

date as ccyymmdd format and
time as hhmmss format

I am able to get date in ccyymmdd using
CONVERT(varchar(8), @.fDate, 112) )

How do I get time in hhmmss format .. its little urgent pls help...

I tried using DATEPART(hh, @.fDate) DATEPART(mm, @.fDate) DATEPART(ss, @.fDate)
how do I make one string of hhmmss..

Is there a better way?How about this:


replace(Convert (varchar(8),GetDate(), 108),':','')

Is it going to work for you?
First, you get hh:mm:ss and then you replace : with empty string.|||

select convert(varchar, getdate(), 108)

hth|||Waow.. Replace convert combo worked perfectly fine..

Thx....|||Another problem I am running into is this

if I write SELECT LEN('2000') I get answer = 4

However I write function for this I get wrong answer... I always get 1

Here is my function.. can anyone tell whats wrong?
CREATE FUNCTION fnc_GetLen (@.str nvarchar)
RETURNS nvarchar(10)
AS
BEGIN

DECLARE @.L nvarchar(10)

SET @.L = LEN(@.str)
RETURN (@.L)
END|||Not so sure what the purpose of this function since it does exactly what LEN does.

Anyway, the problem is you did not give a length on the input string. Try change to this:


CREATE FUNCTION fnc_GetLen (@.str nvarchar(500))
|||I just need to find length.. once I find length I do processing inside that function.. like appending 0's or spaces etc..

I will give it a try.. thanks|||also your return type should be int and not nvarchar.

RETURNS int

hth|||Return nvarchar worked perfectly fine. No Problem at all...

I am using padding function and its giving me nightmare when I use blank space (white space) as padding char. Can you see whats wrong?

CREATE FUNCTION fnc_AddPadding ( @.text nvarchar(30), @.padChar char(1), @.maxLen int, @.padType char(1))
RETURNS nvarchar(50)
AS
BEGIN
DECLARE @.resultText nvarchar(50)
SET @.resultText = ''

-- Left Padding
IF @.padType = 'L'
BEGIN
SET @.resultText =RIGHT( REPLICATE ( @.padChar, @.maxLen) + @.text, @.maxLen )
END

-- Right Padding
IF @.padType = 'R'
BEGIN
SET @.resultText = LEFT( @.text + REPLICATE ( @.padChar, @.maxLen) , @.maxLen )
END

-- No Padding
IF @.padType not in ( 'R', 'L')
BEGIN
SET @.resultText = NULL
END

RETURN @.resultText
END

For every other padding char it works ok.. but when I use white space as pad char it is bad...

My Return Type nvarchar(50) or nvarchar(512) and mann..... instead of 5 - 10 white space I end up with 50 or 512 white space...

No comments:

Post a Comment