I want to select records by date using variable.
DECLARE #estDate datetime
SET #estDate = (SELECT GETDATE())
SELECT Meta FROM T_TData WHERE Estt_Date=#estDate
My table:
Meta
Estt_Date
12
2023-01-31 16:34:36.143
99
2023-01-31 16:34:36.143
45
2022-12-31 16:34:30.145
95
2023-01-25 16:34:36.143
My meta column in table int and Estt_Date is datetime.
How can I select records of particular date using variable.
You can do this. Please find the following example
CREATE TABLE #tempData
(
Meta INT,
Estt_Date DATETIME
)
INSERT INTO #tempData(Meta,Estt_Date)
VALUES
(12,'2023-01-31 16:34:36.143'),
(12,'2023-01-31 16:34:36.143'),
(12,'2022-12-31 16:34:30.145'),
(12,'2023-01-25 16:34:36.143')
SELECT * FROM #tempData
DECLARE #estDate DATE = CAST(GETDATE() AS DATE)
SELECT * from #tempData WHERE CAST(Estt_Date AS DATE)=#estDate
DROP TABLE IF EXISTS #tempData
DECLARE #ESTDATE DATE
SET #ESTDATE=GETDATE()
SELECT META FROM T_TDATA WHERE ESTT_DATE>=#ESTDATE AND ESTT_DATE<DATEADD(DD,1,#ESTDATE)
Related
Two Column in table tblpress
Date Time
20160307 120949
20160307 133427
Need to be select below the format:
07-03-2016 12:09:49
07-03-2016 13:34 27
or
03-March-2016 12:09: 49 PM
03-March-2016 01:34: 27 PM
You can try below
select format(cast([Date] as date),'dd-MMMM-yyyy') as [Date],
TIMEFROMPARTS(LEFT([Time],2), SUBSTRING([Time],3,2), RIGHT([Time],2), 0,0) as [Time]
I think CAST/CONVERT will help you:
SELECT
CAST('20160307' AS date),
CAST(STUFF(STUFF('120949',3,0,':'),6,0,':') AS time)
And convert for out:
SELECT
CONVERT(varchar(20),NormalDate,105) OutDate, -- Italian style
CONVERT(varchar(20),NormalTime,108) OutTime -- hh:mi:ss
FROM
(
SELECT
CAST([Date] AS date) NormalDate,
CAST(STUFF(STUFF([Time],3,0,':'),6,0,':') AS time) NormalTime
FROM YourTable
) q
CAST and CONVERT (Transact-SQL)
And you can use FORMAT (Transact-SQL)
SELECT
FORMAT(GETDATE(),'dd-MM-yyyy'),
FORMAT(GETDATE(),'HH:mm:ss')
Best way to do it is to create a function :
create FUNCTION [dbo].[udfGetDateTimeFromInteger]
(
#intDate int,
#intTime int
)
RETURNS datetime
AS BEGIN
-- Declare the return variable here
DECLARE #DT_datetime datetime = NULL,
#str_date varchar(11),
#str_time varchar(8)
if(#intDate is not null and #intDate > 0)
begin
select #str_date = CAST( cast(#intDate as varchar(8)) AS date)
if #intTime=0
select #str_time ='000000'
else
select #str_time = right('0'+CONVERT(varchar(11),#intTime),6)
select #str_time =
SUBSTRING(#str_time,1,2)+':'+SUBSTRING(#str_time,3,2)+':'+SUBSTRING(#str_time,5,2)
select #DT_datetime = CAST(#str_date+' '+#str_time as datetime)
end
-- Return the result of the function
RETURN #DT_datetime
END
and then call it in select like :
declare #next_run_date int, #next_run_time int
select #next_run_date = 20160307
select #next_run_time = 130949
SELECT #next_run_date inputdate,
#next_run_time inputtime,
dbo.udfGetDateTimeFromInteger(#next_run_date, #next_run_time) outputdatetime
Output will be like :
inputdate inputtime outputdatetime
20160307 130949 2016-03-07 13:09:49.000
You said those are numbers, right? You can use datetimefromparts (or datetime2fromparts). ie:
select
datetimefromparts(
[date]/10000,
[date]%10000/100,
[date]%100,
[time]/10000,
[time]%10000/100,
[time]%100,0)
from tblpress;
DB Fiddle demo
Note that naming fields like that and also storing date and time like that is a bad idea.
I later noticed it was char fields:
select
cast([date] as datetime) +
cast(stuff(stuff([time],5,0,':'),3,0,':') as datetime)
from tblpress;
I am dealing with the holiday table of a application and I have to find the next working days based on the holiday list in that table .
If the input is a working day, we expect a blank/NULL to be returned, but if it is a holiday, we expect the next working day to be returned.
My holiday table contains below sample data.
First date column is for startdate and second one is for enddate. Instead of using startdate and enddate for two consecutive holidays. Client have created two separate rows.
Now I have to write a select query which will give the next working days based on that sample data.
Suppose if I am passing '2016-04-20 00:00:00.000' as the conditional date then the query should return '2016-04-22 00:00:00.000' as the working date and there are consecutive two holidays.
2016 2016-04-20 00:00:00.000 2016-04-20 00:00:00.000 Test
2016 2016-04-21 00:00:00.000 2016-04-21 00:00:00.000 Test2
2016 2016-04-28 00:00:00.000 2016-04-28 00:00:00.000 Test3
You can try this:
--create table holidays(y int, ds datetime, de datetime, hname varchar(10));
--insert into holidays values
--(2016,'2016-04-20 00:00:00.000','2016-04-20 00:00:00.000','Test'),
--(2016,'2016-04-21 00:00:00.000','2016-04-21 00:00:00.000','Test2'),
--(2016,'2016-04-28 00:00:00.000','2016-04-28 00:00:00.000','Test3'),
--(2016,'2016-04-22 00:00:00.000','2016-04-22 00:00:00.000','Test4')
CREATE FUNCTION dbo.getNextDate(#dateToCheck datetime) RETURNS Datetime
AS
BEGIN
RETURN(
select top 1 dateadd(d,1,de) from
(select y,
MIN(ds) as ds,
MAX(ds) as de
from
(
Select
*,
ROW_NUMBER() OVER(ORDER BY ds asc) as ranking
from holidays
) t
group by y,(CAST(ds AS INT)-Ranking)
)t
where #dateToCheck BETWEEN ds AND de
)
END
Upon testing:
SELECT dbo.getNextDate('2016-04-23 00:00:00.000')-- returns NULL
SELECT dbo.getNextDate('2016-04-21 00:00:00.000')-- returns 2016-04-23 00:00:00.000
SQL demo link
Let me know if the below mentioned code works.This code first makes a calendar table and then excludes Saturday and Sunday from the dates.
declare #mn date = (select min(yourdate) from table)
select top 1 a.caldate
from
(
select dateadd(dd,row_number() over (order by (select 1)) - 1,#mn) as caldate
from sys.all_objects
) as a
where a.caldate not in (select cast(yourdate as date) as yourdate from TableA) and datename(dw,a.caldate) not in ('Saturday','Sunday') and a.caldate >= '2016-04-20'
Suposing a holidays table with this structure:
CREATE TABLE holidays (
[year] int,
[ds] datetime,
[de] datetime,
[description] nvarchar(50)
)
You can create a function that iterates through dates until it finds the correct one
CREATE FUNCTION dbo.getNextDate(#dateToCheck datetime) RETURNS Datetime
AS
BEGIN
DECLARE #tempDate datetime
SET #tempDate=DATEADD(day,1,#dateToCheck)
WHILE EXISTS(SELECT * FROM holidays WHERE #tempDate BETWEEN ds AND de)
BEGIN
SET #tempDate=DATEADD(day,1,#tempDate)
END
RETURN #tempDate
END
This is a very rudimentary first aproximation but it should work.
I'm trying to set a column with a default value or binding of the current date in MSSQL.
I'm currently using GETDATE(), but this gives me the timestamp with the hours, minutes, seconds and milliseconds, I only need the day part (2015-03-05).
Only results I found on the web were these of changing it in the SELECT statement.
If you use it in a date context SQL Server will auto cast it for you
DECLARE #date DATE = GETDATE();
SELECT #date
-- result: 2015-03-05
or you could simply use a cast
SELECT CAST(GETDATE() as DATE)
EDIT:
I'm still not sure if I get what you want, but if you want to do it as a default constraints it works the same way:
create table #table
(
id int,
insertDate date default GETDATE()
)
insert into #table (id) values (1)
select top 1 insertDate from #table
-- result: 2015-03-05
If you want to store only date, excluding time you can use this:
CREATE TABLE #dts(id INT IDENTITY, d_date datetime2 DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
However it will return you zeroes instead of time, as seen here:
id d_date
-------------------------------
1 2015-03-05 00:00:00.0000000
You can remove unwanted characters using LEFT function:
SELECT id, LEFT(d_date, 10) FROM #dts
It will return you:
id d_date
--------------
1 2015-03-05
You could achieve this by using varchar as datatype, but i dont think it would be appropiate solution and it's better to format date in select statement. But if you really need it, then this works:
CREATE TABLE #dts(id INT IDENTITY, d_date VARCHAR(10) DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
Output:
id d_date
--------------
1 2015-03-05
Set your default value on the column to
(CONVERT([date],getdate(),0))
I have used it many times
In other ways to convert DATETIME to DATE (get only date without time) you can use CAST to DATE format.
SELECT CAST(GETDATE() AS DATE)
In your case you can set default value type DATE without CASTing.
CREATE TABLE #TempTable
(
Id INT,
..... ,
CurrentDate DATE DEFAULT GETDATE()
)
The answer to your problem is simple. Change the format of the column that is going to hold the value to a DATE (as opposed to a data type that will hold the time portion, i.e: DATETIME).
Then set the default to GETDATE() and because the destination column is a DATE the time portion will be stripped off for you.
Take this sample code:
CREATE TABLE #temp (id INT, CreatedDate DATE DEFAULT GETDATE())
INSERT INTO #temp ( id)
VALUES ( 1 ),( 2 ),( 3 )
SELECT * FROM #temp
DROP TABLE #temp
Output:
id CreatedDate
1 2015-03-05
2 2015-03-05
3 2015-03-05
You can use CONVERT() to get date in different formats. From http://www.w3schools.com/sql/func_convert.asp :
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
gives you the following results:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243
i'm trying to do this line of sql script
select *
from content
where first_broadcast_date <= CONVERT(datetime, '26-11-2014', 105)
the result show me the content which have the value of 'first_broadcast_date' less than '26-11-2014' but not the content which have 'first_broadcast_date = 26-11-2014'
the type of 'first_broadcast_date' field is datetime2(7)
because its a date time field you either have a choice to convert to date might give you a bad performance or you can pass date by concatenating 23:59:59 so that you can filter any row in that day
CREATE TABLE #t (id INT IDENTITY(1,1), d DATETIME2(7))
INSERT INTO #t (d)
VALUES(GETDATE())
SELECT * FROM #t WHERE d <= '02/12/2015 23:59:59'
I have data of the following format:
Date Value
08/28 100
09/01 1
09/01 5
09/10 2
I would like my output to be:
Date Value
08/28 100
08/29 100
08/30 100
08/31 100
09/01 106
09/02 106
.
.
.
09/10 108
I'm just getting started with SQL, so any help would be appreciated. What I have right now is below, but that's not really close to what I seek:
SELECT Date, COUNT(DISTINCT(Service)) AS Value
FROM [Directory]
WHERE Date <= #myDate
GROUP BY Date ORDER BY Date
First, you can use a sub query to get the aggregate values
SELECT Date, (SELECT SUM(Value) FROM Directory d WHERE d.Date <= Directory.Date)
FROM [Directory]
WHERE Date <= #myDate
ORDER BY Date
Which would give you something that looks like this:
Date Value
08/28 100
09/01 101
09/01 106
09/10 108
Then you can add a Date table as sgeddes suggested. This article explains if fairly well: http://michaelmorley.name/how-to/create-date-dimension-table-in-sql-server
Then you can modify your query like so
SELECT DateTable.Date, (SELECT SUM(Value) FROM Directory d WHERE d.Date <= Directory.Date)
FROM [Directory] LEFT OUTER JOIN DateTable on Directory.Date = DateTable.Date
WHERE DateTable.Date <= #myDate
ORDER BY DateTable.Date
To get the data format you're looking for.
Based on sgeddes suggestion:
SELECT a.Date, COUNT(DISTINCT(d.Service)) AS Value
FROM [Directory] d
LEFT OUTER JOIN [Date Table] a on d.Date = a.Date
WHERE Date <= #myDate
GROUP BY Date
ORDER BY Date
Use following script in sqlserver :
BEGIN
--If exist then drop temp tables
DROP TABLE #YOURTABLE;
DROP TABLE #TEST1;
DECLARE #MINDATE DATETIME;
DECLARE #MAXDATE DATETIME;
CREATE TABLE #YOURTABLE(
CDATE DATE,
VALUE INT
);
INSERT INTO #YOURTABLE VALUES ('08/28/2014',100),('09/01/2014',1),('09/01/2014',5),('09/10/2014',100);
--select start date and end date from your table
SELECT #MINDATE=MIN(CDATE),#MAXDATE=MAX(CDATE) FROM #YOURTABLE;
CREATE TABLE #TEST1(
CDATE DATE,
VALUE INT
);
;WITH CALENDAR
AS (
SELECT #MINDATE CDATE
UNION ALL
SELECT CDATE + 1
FROM CALENDAR
WHERE CDATE + 1 <= #MAXDATE
)
-- insert all dates with 0 value in temp table
INSERT INTO #TEST1 SELECT CDATE,0 FROM CALENDAR;
--delete dates which are already there in your table
DELETE FROM #TEST1 WHERE CDATE IN (SELECT CDATE FROM #YOURTABLE)
-- insert all dates with values from your table to temporary table which holds dates which are not in your table
INSERT INTO #TEST1 SELECT * FROM #YOURTABLE;
SELECT T1.CDATE,(SELECT SUM(VALUE) FROM #TEST1 T2 WHERE T2.CDATE<=T1.CDATE) FROM #TEST1 T1
END