How to remove formatting from the GETDATE() command

Asked

Viewed 1,099 times

5

I am developing an application that will be used by several customers simultaneously, I would like to use as id the Day, Month, Year, Hour, Minute, Second and Millisecond, would have as I remove the / and : that the function GETDATE() returns?

2 answers

6

4

If it is SQL-SERVER 2008 or earlier, the function FORMAT, very well applied by friend @gmsantos won’t work; You can do this function to remove special characters:

CREATE FUNCTION [dbo].[fn_StripCharacters]
(
    @String NVARCHAR(MAX), 
    @MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @MatchExpression =  '%['+@MatchExpression+']%'

    WHILE PatIndex(@MatchExpression, @String) > 0
        SET @String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, '')

    RETURN @String

END

Then just run the query with the function, remembering only to convert the result of GETDATE():

SELECT dbo.fn_StripCharacters(CONVERT(VARCHAR, GETDATE(), 120), '^a-z0-9')

The result will be: 20150528095612

Source: Soen

  • 1

    Well-observed ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.