Modifying an XML - SMALLDATETIME

175 Views Asked by At

Hi I am working with XML in SQL server and trying to use the modify function on a SMALLDATETIME variable but it does not give me desired result.

    DECLARE @Shift_StartDate SMALLDATETIME = '2017-06-05 09:00:00';
DECLARE @Shift_EndDate SMALLDATETIME = '2017-06-05 09:30:00';
DECLARE @x XML = '<dbo.tblXXXX StartDate="" EndDate=""  />'
SET @x.modify('replace value of (/*[1]/@StartDate) with sql:variable("@Shift_StartDate")')
SET @x.modify('replace value of (/*[1]/@EndDate) with sql:variable("@Shift_EndDate")')

SELECT @X

The output is. There are additional '.000' appended at the end. How can I get rid of them.

<dbo.tblXXXX StartDate="2017-06-05T09:00:00.000" EndDate="2017-06-05T09:30:00.000" />

I want the above output to like as shown below as this is what is returned when i run the below query

<dbo.tblXXXX StartDate="2017-06-05T09:00:00" EndDate="2017-06-05T09:30:00" />

DECLARE @ActualXml XML;

SET @ActualXml = (SELECT 
                     [StartDate], 
                     [EndDate]
                     FROM [dbo].[tblXXXX]
                     WHERE UniqueId = 8124X
                     FOR XML AUTO)
SELECT @ActualXml

DataType of [StartDate] and [EndDate] is 'SMALLDATETIME'

I want the XML modify function to return the same result without .000.

Please suggest. Thanks in advance Rao

1

There are 1 best solutions below

0
Shnugo On

You might cast the value to xs:string and use XQuery's substring to cut off the string:

DECLARE @Shift_StartDate SMALLDATETIME = '2017-06-05 09:00:00';
DECLARE @Shift_EndDate SMALLDATETIME = '2017-06-05 09:30:00';
DECLARE @x XML = '<dbo.tblXXXX StartDate="" EndDate=""  />'
SET @x.modify('replace value of (/*[1]/@StartDate) with substring(xs:string(sql:variable("@Shift_StartDate")),1,19)')
SET @x.modify('replace value of (/*[1]/@EndDate) with sql:variable("@Shift_EndDate")')

SELECT @X

The result

<dbo.tblXXXX StartDate="2017-05-06T09:00:00" EndDate="2017-05-06T09:30:00.000" />

StartDate is without .000, while EndDate is unchanged