storing current date time with milisec in varchar column - mssql - sql-server

storing current date time with milisec in varchar column - mssql
i do have a varchar max column
i want to store current date with mili seconds in a column
with Concatenating the day-month-year-h-m-s-ms
Like
2304201310151515

Try this :-
SELECT REPLACE(CONVERT(varchar(max), getdate(), 103), '/', '')+
REPLACE(CONVERT(varchar(max), getdate(), 114), ':', '')

Try this one -
DECLARE #date DATETIME
SELECT #date = GETDATE()
SELECT
REPLACE(CONVERT(VARCHAR(20), #date, 104), '.', '') +
LEFT(REPLACE(CONVERT(VARCHAR(20), #date, 114), ':', ''), 8)
DECLARE #text VARCHAR(20)
SELECT #text = '2304201310151515'
SELECT
CAST(
SUBSTRING(#text, 5, 4) +
SUBSTRING(#text, 3, 2) +
SUBSTRING(#text, 1, 2) AS DATETIME)
+
CAST(
SUBSTRING(#text, 9, 2) + ':' +
SUBSTRING(#text, 11, 2) + ':' +
SUBSTRING(#text, 13, 2) + '.' +
SUBSTRING(#text, 15, 2) AS TIME)

I don't know what you use the varchar column for, but I highly recommend you use the yyyymmddhhmmssmmm format as it is sortable.
declare #date datetime = '20130423 10:15:15.15' -- Works in SQL 2008
select replace(replace(replace(replace(convert(varchar /* defaults to 30 char*/, #date, 121)
, '-', '')
, ':', '')
, '.', '')
, ' ', '')
Also, if you really want 2 digit milliseconds, then limit the characters returned from the convert function to varchar(22).
declare #date datetime = '20130423 10:15:15.15' -- Works in SQL 2008
select replace(replace(replace(replace(convert(varchar(22), #date, 121)
, '-', '')
, ':', '')
, '.', '')
, ' ', '')

Related

Convert varchar string to datetime

I am having an issue converting below to a DateTime, I am only able to get the date portion of the string. My goal is to get both the date & time.
declare #col varchar(14) = '20220602235900';
select CONVERT(datetime, CAST(#col AS varchar(8)), 121) dtimecre
Steps:
Read the documentation for CONVERT and pick the closest format to use
Do some string manipulation to get the desired format
Convert.
DECLARE #col varchar(14) = '20220602235900';
SELECT
CONVERT(date, SUBSTRING(#col,1,8), 121) [Date Component]
, CONVERT(time, SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 8) [Time Component]
, CONVERT(datetime, SUBSTRING(#col,1,4) + '-' + SUBSTRING(#col,5,2) + '-' + SUBSTRING(#col,7,2) + ' ' + SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 120) [DateTime Representation];
Returns:
Date Component
Time Component
DateTime Representation
2022-06-02
23:59:00.0000000
2022-06-02 23:59:00.000
And another variant with a smaller amount of SUBSTRING:
DECLARE #col varchar(14) = '20220602235900';
SELECT DateComponent = CAST(DatePartString AS DATE),
TimeComponent = CAST(TimePartString AS TIME),
DateAndTime = CAST(DatePartString + ' ' + TimePartString AS DATETIME)
FROM (VALUES(#col)) AS O (DateColumn)
CROSS APPLY (
SELECT DatePartString = LEFT(DateColumn, 8),
TimePartString = FORMAT(CAST(SUBSTRING(DateColumn, 9, 6) AS INT), '##:##:##')
) AS String;

Datetime is NULL when time format differs

I have specific time scenario which can be 4 digit, 6 digit or can be NULL or string as mentioned below. Here in scenario 3 & 4 my method of calculating datetime is not working and coming as NULL
Is there any way to get date with 00:00:00:000 as time for case 3 & 4?
& for 1 it should be 10:02:00:000
DECLARE #DATE VARCHAR(10) =CAST(GETDATE() AS DATE)
DECLARE #Time1 VARCHAR(10) = '1002'
DECLARE #Time2 VARCHAR(10) = '160634'
DECLARE #Time3 VARCHAR(10) = '0900XX'
DECLARE #Time4 VARCHAR(10) = ''
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time1), 2)
+ ':' + SUBSTRING(#Time1, 3, 2)
+ ':' + RIGHT(rtrim(#Time1), 2)) , TRY_CONVERT(TIME, #Time1), #Time1 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time2), 2)
+ ':' + SUBSTRING(#Time2, 3, 2)
+ ':' + RIGHT(rtrim(#Time2), 2)) , TRY_CONVERT(TIME, #Time2), #Time2 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time3), 2)
+ ':' + SUBSTRING(#Time3, 3, 2)
+ ':' + RIGHT(rtrim(#Time3), 2)) , TRY_CONVERT(TIME, #Time3), #Time3 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time4), 2)
+ ':' + SUBSTRING(#Time4, 3, 2)
+ ':' + RIGHT(rtrim(#Time4), 2)) , TRY_CONVERT(TIME, #Time4), #Time4 AS Time
I would, personally, "pad out" the values to be 6 digits, inject the : characters, and then use TRY_CONVERT. Then you use ISNULL to return midmight for failed converions:
SELECT ISNULL(TRY_CONVERT(time(0),STUFF(STUFF(RIGHT('000000' + V.VarcharTime,6),5,0,':'),3,0,':')),'00:00:00')
FROM (VALUES(#Time1),
(#Time2),
(#Time3),
(#Time4))V(VarcharTime);
If 1002 is meant to be 10:02:00 rather than 00:10:02 then pad on the right, rather than the left:
SELECT ISNULL(TRY_CONVERT(time(0),STUFF(STUFF(LEFT(V.VarcharTime+'000000',6),5,0,':'),3,0,':')),'00:00:00')
FROM (VALUES(#Time1),
(#Time2),
(#Time3),
(#Time4))V(VarcharTime);
..................
DECLARE #Time4 VARCHAR(10) = ''
select #Time1 = concat(cast(#Time1 as varchar(8)), replicate('0', 8));
select #Time2 = concat(cast(#Time2 as varchar(8)), replicate('0', 8));
select #Time3 = concat(cast(#Time3 as varchar(8)), replicate('0', 8));
select #Time4 = concat(cast(#Time4 as varchar(8)), replicate('0', 8));
SELECT TRY_CONVERT(DATETIME, #DATE +' '......................

Ensuring that a comma is not added if only one record is found, or that both are added

Consider the follow piece of an SQL query that is designed to construct a complex return in the form of XML:
ISNULL(Logbook1 + ',', '') + ISNULL(Logbook2 + ',', '') + ISNULL(Logbook3 + ',', '') AS '#logBookNums',
In essence this will search the appropriate record. If it finds that no records exist for LogBook1, LogBook2 or LogBook3 it will return an empty string. If it finds one record in LogBook1 it will return that and one trailing comma.
Unfortunately the WCF service to which this XML is being sent is appallingly documented (for which in truth read none whatsoever) and it is rejecting a single logbook number with a trailing comma.
My guess is that it should either be submitted as:
logBookNums="12345,,"
Or
logBookNums="12345"
How should I alter the above line of SQL to output one or the other, and (if the query finds two logbook numbers) to produce output like this:
logBookNums="12345,12346,"
Or
logBookNums="12345,12346"
This is the entire query into which I would need to insert a solution to handle this predicament for both #logBookNums and #landingDecNums.
CREATE PROCEDURE dbo.CreateErsSalesAddSubmissionXmlByDateRange
-- Add the parameters for the stored procedure here
#uname VARCHAR(10) ,
#pword VARCHAR(10) ,
#sntype VARCHAR(1) ,
#action VARCHAR(10) ,
#salesContractRef VARCHAR(10),
#auctionId NCHAR(10) ,
#startDate DATE,
#endDate DATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
RTRIM(#uname) AS '#uname',
RTRIM(#pword) AS '#pword',
(SELECT
#snType AS '#snType',
RTRIM(#action) AS '#action',
COALESCE(#salesContractRef, '') AS '#salesContractRef',
CONVERT(VARCHAR(10), DateOfPurchase, 112) AS '#saleDate',
RTRIM(COALESCE(#auctionID, '')) AS '#auctionID',
ISNULL(Logbook1 + ',', '') + ISNULL(Logbook2 + ',', '') + ISNULL(Logbook3 + ',', '') AS '#logBookNums',
ISNULL(LandingDecNumber1 + ',', '') + ISNULL(LandingDecNumber2 + ',', '') + ISNULL(LandingDecNumber3 + ',', '') AS '#landingDecNums',
COALESCE(VesselName, '') AS '#vesselName',
RTRIM(VesselPLN) AS '#vesselPln',
RTRIM(VesselOwner) AS '#vesselMasterOwner',
COALESCE(CONVERT(VARCHAR(10), LandingDate1, 112), '') AS '#landingDate1',
COALESCE(CONVERT(VARCHAR(10), LandingDate2, 112), '') AS '#landingDate2',
COALESCE(CONVERT(VARCHAR(10), LandingDate3, 112), '') AS '#landingDate3',
RTRIM(CountryOfLanding) AS '#countryOfLanding',
RTRIM(PortOfLanding) AS '#landingPortCode',
RTRIM(lh1.LandingId) AS '#internalRef',
(SELECT
COALESCE(RTRIM(SpeciesCode),'') AS '#speciesCode',
RTRIM(FishingArea) AS '#faoAreaCode',
COALESCE(RTRIM(IcesZone),'') AS '#ZoneCode',
COALESCE(RTRIM(ld.DisposalCode),'') AS '#disposalCode',
COALESCE(ld.FreshnessGrade,'') AS '#freshnessCode',
COALESCE(ld.ProductSize,'') AS '#sizeCode',
COALESCE(ld.PresentationCode,'') AS '#presentationCode',
COALESCE(ld.PresentationState,'') AS '#stateCode',
RTRIM(ld.NumberOfFish) AS '#numberOfFish',
FORMAT(ld.Quantity, 'N2') AS '#weightKgs',
FORMAT(Quantity * ld.UnitPrice, 'N2') AS '#value',
COALESCE(ld.Currency,'') AS '#currencyCode',
RTRIM(ld.WithdrawnDestinationCode) AS '#withdrawnDestinationCode',
RTRIM(ld.BuyersRegistrationCode) AS '#buyerReg',
RTRIM(ld.SalesContractRef) AS '#salesContractRef'
FROM LandingDetails ld
JOIN LandingHeaders lh
ON ld.LandingId = lh.LandingId
WHERE ld.LandingId = lh1.LandingId
FOR XML PATH ('salesline'), TYPE)
FROM LandingHeaders lh1
WHERE lh1.AllocatedErsId IS NULL AND lh1.LandingDate1 BETWEEN #startDate AND #endDate
ORDER BY VesselName,lh1.LandingId
FOR XML PATH ('salesnote'), TYPE)
FOR XML PATH ('ers')
END
GO
EDIT (what I have tried following answer below)
SELECT
RTRIM(#uname) AS '#uname'
,RTRIM(#pword) AS '#pword'
,(SELECT
#snType AS '#snType'
,RTRIM(#action) AS '#action'
,COALESCE(#salesContractRef, '') AS '#salesContractRef'
,CONVERT(VARCHAR(10), DateOfPurchase, 112) AS '#saleDate'
,RTRIM(COALESCE(#auctionID, '')) AS '#auctionID'
,(
SELECT ',' + CAST(LogbookX AS VARCHAR(100))
FROM
(
VALUES(Logbook1),(Logbook2),(Logbook3)
) AS x(LogbookX)
FOR XML PATH('')
),1,1,'')
AS NumList(Concatenated)
WHERE NumList.Concatenated IS NOT NULL AS '#logBookNums'
,ISNULL(LandingDecNumber1 + ',', '') + ISNULL(LandingDecNumber2 + ',', '') + ISNULL(LandingDecNumber3 + ',', '') AS '#landingDecNums'
,COALESCE(VesselName, '') AS '#vesselName'
,RTRIM(VesselPLN) AS '#vesselPln'
,RTRIM(VesselOwner) AS '#vesselMasterOwner'
,COALESCE(CONVERT(VARCHAR(10), LandingDate1, 112), '') AS '#landingDate1'
,COALESCE(CONVERT(VARCHAR(10), LandingDate2, 112), '') AS '#landingDate2'
,COALESCE(CONVERT(VARCHAR(10), LandingDate3, 112), '') AS '#landingDate3'
,RTRIM(CountryOfLanding) AS '#countryOfLanding'
,RTRIM(PortOfLanding) AS '#landingPortCode'
,RTRIM(lh1.LandingId) AS '#internalRef'
Additional edit to help clarify comments from the answer below
The full amended query now looks as follows:
CREATE PROCEDURE dbo.CreateErsSalesAddSubmissionXmlByDateRange
-- Add the parameters for the stored procedure here
#uname VARCHAR(10),
#pword VARCHAR(10),
#sntype VARCHAR(1),
#action VARCHAR(10),
#salesContractRef VARCHAR(10),
#auctionId NCHAR(10),
#startDate DATE,
#endDate DATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
RTRIM(#uname) AS '#uname'
,RTRIM(#pword) AS '#pword'
,(SELECT
#snType AS '#snType'
,RTRIM(#action) AS '#action'
,COALESCE(#salesContractRef, '') AS '#salesContractRef'
,CONVERT(VARCHAR(10), DateOfPurchase, 112) AS '#saleDate'
,RTRIM(COALESCE(#auctionID, '')) AS '#auctionID'
,STUFF
((SELECT
',' + CAST(LogbookX AS VARCHAR(100))
FROM (
VALUES (Logbook1), (Logbook2), (Logbook3)
) AS x (LogbookX)
FOR XML PATH (''))
, 1, 1, '')
AS '#logBookNums'
,ISNULL(LandingDecNumber1 + ',', '') + ISNULL(LandingDecNumber2 + ',', '') + ISNULL(LandingDecNumber3 + ',', '') AS '#landingDecNums'
,COALESCE(VesselName, '') AS '#vesselName'
,RTRIM(VesselPLN) AS '#vesselPln'
,RTRIM(VesselOwner) AS '#vesselMasterOwner'
,COALESCE(CONVERT(VARCHAR(10), LandingDate1, 112), '') AS '#landingDate1'
,COALESCE(CONVERT(VARCHAR(10), LandingDate2, 112), '') AS '#landingDate2'
,COALESCE(CONVERT(VARCHAR(10), LandingDate3, 112), '') AS '#landingDate3'
,RTRIM(CountryOfLanding) AS '#countryOfLanding'
,RTRIM(PortOfLanding) AS '#landingPortCode'
,RTRIM(lh1.LandingId) AS '#internalRef'
,(SELECT
COALESCE(RTRIM(SpeciesCode), '') AS '#speciesCode'
,RTRIM(FishingArea) AS '#faoAreaCode'
,COALESCE(RTRIM(IcesZone), '') AS '#ZoneCode'
,COALESCE(RTRIM(ld.DisposalCode), '') AS '#disposalCode'
,COALESCE(ld.FreshnessGrade, '') AS '#freshnessCode'
,COALESCE(ld.ProductSize, '') AS '#sizeCode'
,COALESCE(ld.PresentationCode, '') AS '#presentationCode'
,COALESCE(ld.PresentationState, '') AS '#stateCode'
,RTRIM(ld.NumberOfFish) AS '#numberOfFish'
,FORMAT(ld.Quantity, 'N2') AS '#weightKgs'
,FORMAT(Quantity * ld.UnitPrice, 'N2') AS '#value'
,COALESCE(ld.Currency, '') AS '#currencyCode'
,RTRIM(ld.WithdrawnDestinationCode) AS '#withdrawnDestinationCode'
,RTRIM(ld.BuyersRegistrationCode) AS '#buyerReg'
,RTRIM(ld.SalesContractRef) AS '#salesContractRef'
FROM LandingDetails ld
JOIN LandingHeaders lh
ON ld.LandingId = lh.LandingId
WHERE ld.LandingId = lh1.LandingId
FOR XML PATH ('salesline'), TYPE)
FROM LandingHeaders lh1
WHERE lh1.AllocatedErsId IS NULL
AND lh1.LandingDate1 BETWEEN #startDate AND #endDate
ORDER BY VesselName, lh1.LandingId
FOR XML PATH ('salesnote'), TYPE)
FOR XML PATH ('ers')
END
GO
when there are logBookNums then we are getting correctly formatted xml as you see below.
However when there aren't we should get logBookNums="" but as you see we get nothing.
You might try it like this
You'll need an "IN"-search, there's no search like aNumber='123,345,678'
DECLARE #tbl TABLE(Logbook1 INT,Logbook2 INT,Logbook3 INT);
INSERT INTO #tbl VALUES
(12345,23456,56789)
,(234,NULL,NULL)
,(NULL,123,NULL)
,(NULL,NULL,NULL);
SELECT 'logbBookNums IN(' + NumList.Concatenated +')'
FROM #tbl
CROSS APPLY
(
SELECT STUFF
(
(
SELECT ',' + CAST(LogbookX AS VARCHAR(100))
FROM
(
VALUES(Logbook1),(Logbook2),(Logbook3)
) AS x(LogbookX)
FOR XML PATH('')
),1,1,'')
)AS NumList(Concatenated)
WHERE NumList.Concatenated IS NOT NULL
The result
logbBookNums IN(12345,23456,56789)
logbBookNums IN(234)
logbBookNums IN(123)
Well you can write it in Case When structure, it is not so long:
CASE WHEN Logbook1 is not null
THEN
CASE WHEN Logbook2 is not null
THEN
CASE WHEN Logbook2 is not null
THEN Logbook1+','+Logbook2+','+Logbook3
ELSE Logbook1+','+Logbook2
ELSE
CASE WHEN Logbook3 is not null
THEN Logbook1+','+Logbook3
ELSE Logbook1
ELSE CASE WHEN ...

combine date and time column problem

Using SQL Server 2005
Date Time
20060701 090000
20060702 020000
20060703 180000
...
Date and Time datatype is varchar
Tried Query
select Convert(datetime, Convert(char(10), date, 103) + ' ' + Convert(char(8), time, 108), 103) from table
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, date)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, time), time)
as datetime) from table
It showing error as out of range value.
How to solve this issue.
Need Sql Query Help
First off, why are you storing a DATETIME in a VARCHAR?
This should be able to help
DECLARE #Table TABLE(
Val VARCHAR(20)
)
INSERT INTO #Table (Val) SELECT '20060701 090102'
INSERT INTO #Table (Val) SELECT '20060702 020000'
INSERT INTO #Table (Val) SELECT '20060703 180000'
SELECT *,
CAST(SUBSTRING(Val,1,8) + ' ' + SUBSTRING(Val,10,2) + ':' + SUBSTRING(Val,12,2) + ':' + SUBSTRING(Val,14,2) AS DATETIME)
FROM #Table
I came across a similar issue a few years ago, when importing HL7 messages. Here is a copy of the function I used. It creates a DateTime string with the time component correctly separated into hh:mm:ss, which is needed for the cast to DateTime.
CREATE FUNCTION fn_StringDateTietoDateTime
(
#Date varchar(15)
)
RETURNS datetime
AS
BEGIN
DECLARE #Result DATETIME
SET #Result = NULL
If len(#Date) > 0
BEGIN
SELECT #Result = CAST(SUBSTRING(#hl7date, 1, 8) + ' ' + SUBSTRING(#hl7date, 10, 2) + ':' +
SUBSTRING(#date, 12, 2) + ':' + SUBSTRING(#date,14, 2) AS DATETIME)
END
RETURN #RESULT
END

Converting DateTime to nvarchar, just month and year

How to convert the datetime value to nvarchar and want to format it "Month, Year" e-g October 1st 2009 value should get converted to "October, 2009"
use this:
select CONVERT(nvarchar(50), DATENAME(m, getdate())
+ ', '
+ DATENAME(yyyy, getdate())
)
OUTPUT:
--------------------------------------------------
October, 2009
(1 row(s) affected)
Try this
DECLARE #DateTime DATETIME
SET #DateTime = '01 Oct 2009'
SELECT #DateTime
SELECT DATENAME(mm, #DateTime) + ', ' + CAST(DATEPART(yy, #DateTime) AS VARCHAR(4))
One way would be to use datename to extract the pieces you needed in name format, so:
select Convert(nvarchar,datename(m,getdate())) + N', ' + Convert(nvarchar,datename
(yy,getdate()))
And replace getdate() with your date variable / field.
The DateName function will provide the formatting you require:
DATENAME(m, date) + ', ' + DATENAME(yyyy, date)
Converting to nvarchar of a specific size can be done through the cast function:
CAST(value AS nvarchar[30])
Try the following query:
Select case Convert(int, day(getdate())) when 1 then '1st' when 2 then '2nd'
when 3 then '3rd' else Convert(varchar, day(getdate()))+'th' end +' '+ Convert(varchar, Datename(m,getdate()))+' ' +Convert(varchar, Datename(yy,getdate())) as Date
You can replace getdate() with any other date.
Please check if it helps.

Resources