DATETIME gives date without time in SQL Server - sql

I have a SQL query which should convert a datetime. I have tried it in different ways but in every way something goes wrong.
INSERT INTO SETTLEMENT_WIN (COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME,
END_TIME)
VALUES ('BE', 'EL', NULL, CONVERT(datetime, '2015-12-14 15:45', 'YYYY-MM-DD HH24:MI'), CONVERT(datetime, '2015-12-14 16:00', 'YYYY-MM-DD HH24:MI'));
gives the error:
Msg 8116, Level 16, State 1, Line 1 Argument data type varchar is
invalid for argument 3 of convert function.
INSERT INTO SETTLEMENT_WIN (COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME,
END_TIME)
VALUES ('BE', 'EL', NULL, CONVERT(datetime, '2008-12-14 15:45', 120), CONVERT(datetime, '2015-12-14 16:00', 120));
Inserts the row but in START_TIME and END_TIME there is only the date but not the time
Then I tried to only insert the time but even then only the date was inserted (I am not allowed to change the date format).
Declare #Date1 datetime ='2008-12-14 15:45';
Declare #Date2 datetime ='2015-12-14 16:00';
INSERT INTO SETTLEMENT_WIN (COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME,
END_TIME)
VALUES ('BE', 'EL', NULL, CONVERT(datetime, #Date1, 108), CONVERT(datetime, #Date2, 108));
What am I doing wrong? I am using Microsoft SQL Server Management Studio 17.
The CREATE statement for my table is:
CREATE TABLE [SETTLEMENT_WIN] ([SW_ID] [numeric](18, 0) IDENTITY(1, 1) NOT NULL,
[COUNTRY] [varchar](32) NOT NULL,
[COMMODITY] [varchar](32) NOT NULL,
[MARKET_PLACE] [varchar](32),
[START_TIME] [date] NOT NULL,
[END_TIME] [date] NOT NULL,
CONSTRAINT [SW_PK]
PRIMARY KEY ([SW_ID]));

Exactly as I suspected:
[START_TIME] [date] NOT NULL,
[END_TIME] [date] NOT NULL,
If you provide a datetime value to a date datatype the time part of the value will be lost. Try:
DECLARE #d date;
SET #d = '2018-08-02T11:15:59.462'
SELECT #d;
Note it returns 2018-08-02. A date is just that, a date. A datetime, datetime2 or datetimeoffset needs to be used to store a date and time. You'll need to fix your table to resolve this:
ALTER TABLE dbo.SETTLEMENT_WIN ALTER COLUMN [START_TIME] datetime2(0) NOT NULL;
ALTER TABLE dbo.SETTLEMENT_WIN ALTER COLUMN [END_TIME] datetime2(0) NOT NULL;
Then you can insert a date and time value in your table.

#SilverFullbuster, you will need the datatype column in START_TIME and END_TIME changed from date to [datetime].
from:
CREATE TABLE [SETTLEMENT_WIN] ([SW_ID] [numeric](18, 0) IDENTITY(1, 1) NOT NULL,
[COUNTRY] [varchar](32) NOT NULL,
[COMMODITY] [varchar](32) NOT NULL,
[MARKET_PLACE] [varchar](32),
[START_TIME] [date] NOT NULL,
[END_TIME] [date] NOT NULL,
CONSTRAINT [SW_PK]
PRIMARY KEY ([SW_ID]));
to
CREATE TABLE [SETTLEMENT_WIN] ([SW_ID] [numeric](18, 0) IDENTITY(1, 1) NOT NULL,
[COUNTRY] [varchar](32) NOT NULL,
[COMMODITY] [varchar](32) NOT NULL,
[MARKET_PLACE] [varchar](32),
[START_TIME] [datetime] NOT NULL,
[END_TIME] [datetime] NOT NULL,
CONSTRAINT [SW_PK]
PRIMARY KEY ([SW_ID]));
and you can pull the starttime/endtime by extracting from the datetime column like this:
SELECT
SW_ID,
COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME=convert(varchar(8), START_TIME, 108),
END_TIME=convert(varchar(8), END_TIME, 108)
FROM
SETTLEMENT_WIN
and results will be like this:

Related

How to optimize sql multiple select queries?

I have a query that calculates wait time for each record from the Transactions table and calculates SUM and MAX wait time for each of the group below based on receivedDate and claimedDt.
Here is a basic query:
SELECT
'2022-06-01' as reportDate,
waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName AS QueueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId,
COUNT(waitTimeSubQuery.id) AS totalCasesWaiting,
SUM(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS sumWaitTimeMinutes,
MAX(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS maxWaitTimeMinutes
FROM (SELECT
id,
currentAssignedQueueId,
queueAccessPointId,
queueName,
queueReportCategory,
queuePriority,
queueOrganizationHierarchyId,
(CASE WHEN (receivedDateUTC > '0001-01-01T00:00:00Z' OR receivedDate > '0001-01-01T00:00:00Z') AND (appointmentDT IS NULL OR appointmentDT < '2022-09-28T12:58:47')
THEN CAST(DateDiff(MINUTE,
CASE WHEN receivedDateUTC > '0001-01-01T00:00:00Z'
THEN CONCAT(SUBSTRING(CAST(receivedDateUTC AS VARCHAR), 0, 19), 'Z')
ELSE TRY_CAST(CONCAT(CONCAT(SUBSTRING(CAST(receivedDate AS VARCHAR), 0, 10), SUBSTRING(CAST(createdDT AS VARCHAR), 10, 9)), 'Z') AS DATETIME2) END,
CASE WHEN claimedDT > '0001-01-01T00:00:00Z' AND claimedDT < '2022-06-01T23:59:00Z' AND transactionStatus != 'WaitingAssignment'
THEN CONCAT(SUBSTRING(CAST(claimedDT AS VARCHAR), 0, 19), 'Z')
ELSE '2022-06-01T23:59:00Z' END
) AS BIGINT)
ELSE 0 END) AS waitTimeMinutes
FROM #transactionsList
WHERE receivedDate <= '2022-06-01T00:00:00'
AND (claimedDT >= '2022-06-02T00:00:00' OR transactionStatus = 'WaitingAssignment')) waitTimeSubQuery
GROUP BY waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId
I want to calculate statistics for each day for the period of 30 days and the only difference is dates used for calculating waitTimeMinutes (based on endDate, claimedDt, receivedDate) and filtering by receivedDate and claimedDt.
I tried to save sub-set of the Transactions data into a table variable and reuse it in multiple select queries to get the statistics for each day, but this script runs too slow
Here is the code:
DECLARE #transactionsList TABLE (
id UNIQUEIDENTIFIER,
currentAssignedQueueId UNIQUEIDENTIFIER,
queueAccessPointId UNIQUEIDENTIFIER,
queueName VARCHAR(100),
queueReportCategory VARCHAR(100),
queuePriority INT,
queueOrganizationHierarchyId UNIQUEIDENTIFIER,
receivedDate DATE,
claimedDT DATE,
transactionStatus VARCHAR(100),
receivedDateUTC DATE,
appointmentDT DATE,
createdDT DATE)
INSERT INTO #transactionsList
SELECT
Transactions.id,
Transactions.currentAssignedQueueId,
Queues.accessPointId as queueAccessPointId,
Queues.name as queueName,
Queues.reportCategory as queueReportCategory,
Queues.priority as queuePriority,
Queues.organizationHierarchyId as queueOrganizationHierarchyId,
Transactions.receivedDate,
Transactions.claimedDT,
Transactions.transactionStatus,
Transactions.receivedDateUTC,
Transactions.appointmentDT,
Transactions.createdDT
FROM Transactions
LEFT JOIN Queues ON Transactions.currentAssignedQueueId = Queues.Id
WHERE Transactions.consumerId = '66458f4a-b3d4-4f80-93d4-5aa3ea123249'
AND Transactions.isActive = 1
AND Transactions.receivedDate <= '2022-06-30T00:00:00'
AND (Transactions.claimedDT >= '2022-06-02T00:00:00' OR Transactions.transactionStatus = 'WaitingAssignment')
--SELECT COUNT(*) FROM #transactionsList
-- 2022-06-01
SELECT
'2022-06-01' as reportDate,
waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName AS QueueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId,
COUNT(waitTimeSubQuery.id) AS totalCasesWaiting,
SUM(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS sumWaitTimeMinutes,
MAX(CASE WHEN waitTimeSubQuery.waitTimeMinutes > 0 THEN waitTimeSubQuery.waitTimeMinutes ELSE 0 END) AS maxWaitTimeMinutes
FROM (SELECT
id,
currentAssignedQueueId,
queueAccessPointId,
queueName,
queueReportCategory,
queuePriority,
queueOrganizationHierarchyId,
(CASE WHEN (receivedDateUTC > '0001-01-01T00:00:00Z' OR receivedDate > '0001-01-01T00:00:00Z') AND (appointmentDT IS NULL OR appointmentDT < '2022-09-28T12:58:47')
THEN CAST(DateDiff(MINUTE,
CASE WHEN receivedDateUTC > '0001-01-01T00:00:00Z'
THEN CONCAT(SUBSTRING(CAST(receivedDateUTC AS VARCHAR), 0, 19), 'Z')
ELSE TRY_CAST(CONCAT(CONCAT(SUBSTRING(CAST(receivedDate AS VARCHAR), 0, 10), SUBSTRING(CAST(createdDT AS VARCHAR), 10, 9)), 'Z') AS DATETIME2) END,
CASE WHEN claimedDT > '0001-01-01T00:00:00Z' AND claimedDT < '2022-06-01T23:59:00Z' AND transactionStatus != 'WaitingAssignment'
THEN CONCAT(SUBSTRING(CAST(claimedDT AS VARCHAR), 0, 19), 'Z')
ELSE '2022-06-01T23:59:00Z' END
) AS BIGINT)
ELSE 0 END) AS waitTimeMinutes
FROM #transactionsList
WHERE receivedDate <= '2022-06-01T00:00:00'
AND (claimedDT >= '2022-06-02T00:00:00' OR transactionStatus = 'WaitingAssignment')) waitTimeSubQuery
GROUP BY waitTimeSubQuery.currentAssignedQueueId,
waitTimeSubQuery.queueAccessPointId,
waitTimeSubQuery.queueName,
waitTimeSubQuery.queueReportCategory,
waitTimeSubQuery.queuePriority,
waitTimeSubQuery.queueOrganizationHierarchyId
And the part from '2022-06-01' repeats 30 times for each day from the range respectively.
Is there any possibility to optimize this script? For my data it runs nearly 49 seconds and the number of the records in the table is only 7kk and it's far way more on other environment.
---EDIT---
Here are the definitions for the tables Transactions and Queues
CREATE TABLE [dbo].[Transactions] (
[id] UNIQUEIDENTIFIER NULL,
[accessPointId] UNIQUEIDENTIFIER NULL,
[isNonLobby] BIT NULL,
[printReceipt] BIT NULL,
[isExpressed] BIT NULL,
[isAssignedBySupervisor] BIT NULL,
[dateAssignedBySupervisor] VARCHAR (30) NULL,
[dateAssignedBySupervisorLocal] DATETIMEOFFSET (7) NULL,
[supervisorOverrideId] UNIQUEIDENTIFIER NULL,
[supervisorId] UNIQUEIDENTIFIER NULL,
[isNewHousehold] BIT NULL,
[householdId] UNIQUEIDENTIFIER NULL,
[receivedDate] DATE NULL,
[receivedDateUTC] DATETIME2 (7) NULL,
[transactionStatus] VARCHAR (20) NULL,
[claimedDT] DATETIME2 (7) NULL,
[claimedDTLocal] DATE NULL,
[initiallyClaimedById] UNIQUEIDENTIFIER NULL,
[completedDT] DATETIME2 (7) NULL,
[appointmentDT] DATETIME2 (7) NULL,
[completedDTLocal] DATE NULL,
[completedById] UNIQUEIDENTIFIER NULL,
[remarks] VARCHAR (MAX) NULL,
[currentAssignedQueueId] UNIQUEIDENTIFIER NULL,
[currentAssignedUserId] UNIQUEIDENTIFIER NULL,
[preTriageTransactionId] UNIQUEIDENTIFIER NULL,
[isAddClaim] BIT NULL,
[receiptId] UNIQUEIDENTIFIER NULL,
[ticketNumber] VARCHAR (100) NULL,
[deliNumber] VARCHAR (100) NULL,
[tasksCount] BIGINT NULL,
[projectedWaitTime] BIGINT NULL,
[actualWaitTimeMinutes] BIGINT NULL,
[assignWaitTime] BIGINT NULL,
[transactionTimeMinutes] BIGINT NULL,
[triageTimeMinutes] BIGINT NULL,
[outcomeId] UNIQUEIDENTIFIER NULL,
[outcomeReasonId] UNIQUEIDENTIFIER NULL,
[outcomeType] VARCHAR (50) NULL,
[dueDate] VARCHAR (30) NULL,
[dueDateLocal] DATETIMEOFFSET (7) NULL,
[isDueDateToday] VARCHAR (30) NULL,
[isUnknownHousehold] BIT NULL,
[activityId] UNIQUEIDENTIFIER NULL,
[programId] UNIQUEIDENTIFIER NULL,
[reviewMonthDueDate] VARCHAR (40) NULL,
[reviewMonthDueDateLocal] DATETIMEOFFSET (7) NULL,
[officeId] UNIQUEIDENTIFIER NULL,
[isOnceManuallyPaused] BIT NULL,
[pkey] VARCHAR (100) NULL,
[isActive] BIT NULL,
[consumerId] UNIQUEIDENTIFIER NULL,
[organizationName] VARCHAR (50) NULL,
[modifiedBy] UNIQUEIDENTIFIER NULL,
[modifiedDT] DATETIME2 (7) NULL,
[modifiedDTLocal] DATE NULL,
[createdBy] UNIQUEIDENTIFIER NULL,
[createdDT] DATETIME2 (7) NULL,
[createdDTLocal] DATE NULL,
[_ts] BIGINT NULL,
[type] VARCHAR (50) NULL,
[timezoneId] VARCHAR (50) NULL
);
CREATE TABLE [dbo].[Queues] (
[id] UNIQUEIDENTIFIER NULL,
[name] VARCHAR (255) NULL,
[accessPointId] UNIQUEIDENTIFIER NULL,
[organizationHierarchyId] UNIQUEIDENTIFIER NULL,
[assignedOrganizationHierarchyLevel] VARCHAR (20) NULL,
[bundlingGroup] BIGINT NULL,
[reportCategory] VARCHAR (100) NULL,
[priority] INT NULL,
[businessProcessThreshold] BIGINT NULL,
[calculateProjectedWaitTime] BIT NULL,
[waitTimeUnits] VARCHAR (10) NULL,
[hasCarryOver] BIT NULL,
[defaultTransactionTimeMinutes] BIGINT NULL,
[latestQueueMetricId] UNIQUEIDENTIFIER NULL,
[isAppointment] BIT NULL,
[consumerId] UNIQUEIDENTIFIER NULL,
[organizationName] VARCHAR (50) NULL,
[modifiedBy] UNIQUEIDENTIFIER NULL,
[modifiedDT] DATE NULL,
[createdBy] UNIQUEIDENTIFIER NULL,
[createdDT] DATE NULL,
[_ts] BIGINT NULL
);
And an index for the Transactions table (this is the only one index for this table and there are no indexes for the Queues table):
CREATE NONCLUSTERED INDEX [nci_wi_Transactions_EBAFDE3A7C2969265E76135FBA69188D] ON [dbo].[Transactions]
(
[consumerId] ASC,
[isActive] ASC,
[receivedDate] ASC
)
INCLUDE([appointmentDT],[claimedDT],[createdDT],[currentAssignedQueueId],[id],[receivedDateUTC],[transactionStatus]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
Here is the link on GitHub for the execution plan and the full query
https://github.com/sskotliar/query_optimization
PasteThePlan link
Option - 1
You can improve the performance of your query by using a CTE. How does CTE work? The query you write inside the WITH command is executed only once, and its result is stored as a temporary table. This allows you to execute your large query with multiple join in it once. In the remaining cases, only its result is used. But as I understood you call your query with different filters. If this is true, so please see Option 2.
Option - 2
If the result of your repeatable query is large, and you call this query with different filters, it is recommended that you, insert result of repeatable query into temp table, then create needed indexes for this temp table. Then you can use that table as much as you need. Since your table has indexes so your filters will be works high performance.
For each of the options mentioned above, it is recommended that you view Query Plan. Because the query plan may change from the DB side depending on the count of records in the tables.

Create table with condition

I'm creating a table, which will have a date in one of two columns, or neither.
I'd like the third to auto populate with one of these values, without using an update.
CREATE TABLE [table1]
(
id [BIGINT] NOT NULL,
[date1] [DATETIME] NULL,
[date2] [DATETIME] NULL,
[date] AS (CASE
WHEN [date1] IS NOT NULL THEN [date1]
WHEN [date2] IS NOT NULL THEN [date2]
ELSE NULL
END)
)
This doesn't seem to work when I test using:
INSERT INTO [table1] (id, date1)
VALUES (1, GETDATE())
Can anyone help?
Your code appears to be fine, as seen in this db<>fiddle. However, I would suggest using COALESCE() instead of CASE:
CREATE TABLE [table1] (
id [bigint] NOT NULL,
[date1] [datetime] NULL,
[date2] [datetime] NULL,
[date] AS ( COALESCE(date1, date2) )
);
It is more concise.

SQL Server - Operand type clash: numeric is incompatible with datetimeoffset

i am having issue with passing the data from one table to another due to data type.
I tried converting datetimeoffset into date, and inserting into table where i have it as date type and im still getting this error.
this is the format of date/time i have:
2018-12-12 13:00:00 -05:00 in one table, and i have to just pars time and insert it into new table. I tried with casting using ,
CAST([from] AS date) DATE_FROM
I can run the query as select and it works but the moment i try to insert the data into other table even if the other table is formatted and prepared as date type i still get the issue.
Here is the table that stored data with datetimeoffset:
[dbo].[tmp_count](
[elements_Id] [numeric](20, 0) NULL,
[content_Id] [numeric](20, 0) NULL,
[element_Id] [numeric](20, 0) NULL,
[element-name] [nvarchar](255) NULL,
[sensor-type] [nvarchar](255) NULL,
[data-type] [nvarchar](255) NULL,
[from] [datetimeoffset](0) NULL,
[to] [datetimeoffset](0) NULL,
[measurements_Id] [numeric](20, 0) NULL,
[measurement_Id] [numeric](20, 0) NULL,
[from (1)] [datetimeoffset](0) NULL,
[to (1)] [datetimeoffset](0) NULL,
[values_Id] [numeric](20, 0) NULL,
[label] [nvarchar](255) NULL,
[text] [tinyint] NULL
And I am trying to cast columns with datetimeoffset to date and time and push it to #tmp1 table with
SELECT [elements_Id]
,[content_Id]
,[element_Id]
,[element-name]
,[sensor-type]
,[data-type]
,CAST([from] AS date) DATE_FROM
,[to]
,[measurements_Id]
,[measurement_Id]
,CAST([from (1)] AS time (0)) TIME_FROM
,CAST([to (1)] AS TIME(0)) TIME_TO
,[values_Id]
,[label]
,[text]
INTO #Tmp1
FROM [VHA].[dbo].[tmp_count]
SELECT
FROM #tmp1
which gives me the time in format for DATE_FROM as 2018-12-12 and for the DATE_FROM and DATE_TO as 13:00:00 which is exactly what i need.
Now i am trying to splice this table with another table and push it in final table that looks like this:
[dbo].[tbl_ALL_DATA_N](
[serial-number] [nvarchar](255) NULL,
[ip-address] [nvarchar](255) NULL,
[name] [nvarchar](255) NULL,
[group] [nvarchar](255) NULL,
[device-type] [nvarchar](255) NULL,
[elements_Id] [numeric](20, 0) NULL,
[content_Id] [numeric](20, 0) NULL,
[element_Id] [numeric](20, 0) NULL,
[element-name] [nvarchar](255) NULL,
[sensor-type] [nvarchar](255) NULL,
[data-type] [nvarchar](255) NULL,
[DATE_FROM] [date] NULL,
[to] [datetimeoffset](0) NULL,
[measurements_Id] [numeric](20, 0) NULL,
[measurement_Id] [numeric](20, 0) NULL,
[TIME_FROM] [time](0) NULL,
[TIME_TO] [time](0) NULL,
[values_Id] [numeric](20, 0) NULL,
[label] [nvarchar](255) NULL,
[text] [tinyint] NULL
using query below:
INSERT INTO [dbo].[tbl_ALL_DATA_N]
([serial-number],
[ip-address],
[name],
[group],
[device-type],
[measurement_id],
TIME_FROM,
TIME_TO,
[content_id],
[elements_id],
[element-name],
[sensor-type],
[data-type],
DATE_FROM,
[to],
[element_id],
[measurements_id],
[values_id],
[label],
[text])
SELECT *
FROM [VHA].[dbo].[tmp_sensor_info] A
FULL OUTER JOIN #tmp1 B
ON 1 = 1
And here is another message im getting: Msg 206, Level 16, State 2, Line 25
Operand type clash: numeric is incompatible with time
Any ideas?
The solution, which #PanagiotisKanavos alluded to in the comments, is to explicitly list the columns in your final SELECT * FROM.... The order of the columns in that SELECT statement aren't lining up with the columns you're INSERTing into in the destination table.
You may need to run an ad hoc instance of the query to sort out the column order. And then do yourself a favor for future maintenance and be sure to include a table alias on all of the listed columns so you (or whoever has to look at the code next) can easily find out if data is coming from [VHA].[dbo].[tmp_sensor_info] or #tmp1.
This is just one of many dangers in using SELECT * in production code. There's a ton of discussion on the issue in this question: Why is SELECT * considered harmful?
Also, as long as you're in there fixing up the query, consider meaningful table aliases. See: Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3).

Return zero for time slot if data is not present

I'm trying to get data for a period of two minutes every minute there should be data for each second for mid,sid,pid combination. if data is not present for a second for each combination it should return IC value as zero.For two minutes there will be 120 time slots if data is not present for mid,sid, pid combination for any time slot it should return zero.This data is used to plot line chart if data is not present it should go down to zero.
CREATE TABLE [dbo].[DeviceData](
[Id] [BIGINT] IDENTITY(1,1) NOT NULL,
[MId] [INT] NOT NULL,
[SId] [INT] NOT NULL,
[PId] [INT] NOT NULL,
[DataTime] [DATETIME] NOT NULL,
[IC] [INT] NOT NULL,
CONSTRAINT [PK_DeviceData] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
SELECT [MId] ,
[SId] ,
[PId] ,
[DataTime] ,
SUM([IC]) AS Value
FROM [DeviceData]
WHERE DataTime BETWEEN DATEADD(MINUTE, -2, GETUTCDATE())
AND GETUTCDATE()
GROUP BY [MId] ,
SID ,
PId ,
[DataTime];
You need a numbers CTE:
with Numbers as
(
select 1 as NN
union all
select NN+1
from Numbers
where NN < 120
)
, Times as
(
select dateadd(ss,
NN,
DATEADD(MINUTE,
-2,
dateadd(ms,
-datepart(ms,
GETUTCDATE()),
GETUTCDATE()) ) as Timeslot
from Numbers
)
select Timeslot, DD.*
from Times
left join DeviceData DD
on Timeslot = dateadd(ms, -datepart(ms, GETUTCDATE()),GETUTCDATE())
OPTION (MAXRECURSION 1000) -- This will bypass the recursion error

Create Table column date format dd-mm-yyyy SQL Server

I have a table where there are 3 columns to store different dates for different purposes. I would like to store the date in dd-mm-yyyy. Below is the code:
create table PoojaDetails
(
PoojaDetailsID int identity constraint pk_PoojaDetailsID Primary Key,
ReceiptNo AS 'PB' + '/' + cast(datepart(yy,getdate()) as varchar(25)) + '/' + RIGHT('000000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 9) ,
ReceiptDate date not null constraint df_ReceiptDate default convert(date,getdate()),
FirstName varchar(100) not null,
LastName varchar(100) not null,
TelNo bigint,
Star char(50) not null,
Rasi char(50) not null,
Gothram char(100) not null,
PoojaDietyMasterID int not null,
Schedule char(1) not null constraint df_schedule default 'F',
PoojaDate date not null constraint df_pdate default convert(date, '29122013'),
PayMode bit not null,
isDonate bit not null constraint df_isDonate default 1,
DonateAmount float(10),
ChequeNo int,
BankName varchar(255),
ChequeDated date,
UserID int,
SupID int,
ChangeDate date,
Remarks varchar(255),
isPrint char(1) constraint df_isPrint default 'N',
isDeleted bit not null constraint df_isDeleted default 1
)
I would like to have the format for:
ReceiptDate
PoojaDate
ChequeDate
ChangeDate
Thanks :)
Your best bet will be to store the date (if you are using SQL 2008, you should use the DATE datatype) in the universal format of yyyymmdd in the database and then use
CONVERT(Date,YourColumn,105)
when reading the data, to get it in the format you desire.
CONVERT(VARCHAR(10), ReceiptDate, 105) AS [DD-MM-YYYY]
CONVERT(VARCHAR(10), PoojaDate, 105) AS [DD-MM-YYYY]
CONVERT(VARCHAR(10), ChequeDate , 105) AS [DD-MM-YYYY]
use this link for referrence....