How to delete the rows older then 1 month? - sql-server

I have One Table Login in this table i want to delete rows older then 1 months.
CREATE TABLE [dbo].[Login] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[CurrentTime] VARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
This is my table design.Here I am storing date and time as varchar type.
With using or without using the CurrenTime field how to delete one month older rows

Use DateAdd. Try
DELETE FROM Table1 WHERE Column < DATEADD(MONTH, -1, GETDATE())
or
DELETE FROM Table1 WHERE Column < DATEADD(dd,-30,GETDATE())
To convert your varchar column to date format use
SELECT CONVERT(Datetime, '2015-10-29 15:01:00', 120)

DELETE FROM [dbo].[Login]
WHERE [CurrentTime] < DATEADD(month, -1, GETDATE())
will work.

Try :
DELETE FROM Table1 WHERE DATEDIFF(mm, CAST(COL2 AS DateTime), GETDATE()) > 1

Related

ADD day month year quarter to a table based on a date column in the same table

I have a table that contains a column date, I want to add to the the same table 4 other columns DAY, MONTH, YEAR, QUARTER based on the value of the column date for all the records in the table. How could it be done please ?
Option 1 - computed columns via datepart
ALTER TABLE dbo.MyTable
ADD TheYear = DATEPART(YEAR, DateColumn);
ALTER TABLE dbo.MyTable
ADD TheQuarter = DATEPART(QUARTER, DateColumn);
ALTER TABLE dbo.MyTable
ADD TheMonth = DATEPART(MONTH, DateColumn);
ALTER TABLE dbo.MyTable
ADD TheDay = DATEPART(DAY, DateColumn);
This adds virtual, read-only columns to your table based on the value of your source column. This is likely the easiest, least approach unless you have not supplied all the relevant points.
Option 2 - Add columns
ALTER TABLE dbo.MyTable
ADD TheYear int;
ALTER TABLE dbo.MyTable
ADD TheQuarter tinyint;
ALTER TABLE dbo.MyTable
ADD TheMonth tinyint;
ALTER TABLE dbo.MyTable
ADD TheDay tinyint;
This is likely going to cause you pain as there is nothing ensuring the values stored in those 4 columns has any bearing on the value in your original Date column but it's an approach.
And since you're tagging SSIS, if you are trying to do this in a data flow - don't. Write the query to do it and bring this data into your pipeline
SELECT T.*
, TheYear = DATEPART(YEAR, T.DateColumn);
, TheQuarter = DATEPART(QUARTER, T.DateColumn);
, TheMonth = DATEPART(MONTH, T.DateColumn);
, TheDay = DATEPART(DAY, T.DateColumn);
FROM dbo.MyTable AS T;

Build datetime in SQL Server 2012

I need to build a datetime in a select statement based on another 2 columns (datetime).
I cannot seem to get the conversion correct. Can you spot what I am doing wrong?
It seems to me that DatePart it omits the "0" part of the day
Below script should create all the data necessary
IF EXISTS (SELECT * FROM sys.databases WHERE name='TestDB')
BEGIN
ALTER DATABASE TestDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE TestDB
END
CREATE DATABASE TestDB
GO
IF OBJECT_ID(N'[dbo].[TestTable]','U') IS NOT NULL
DROP TABLE [dbo].[TestTable]
GO
CREATE TABLE [dbo].[TestTable]
(
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[DateSample1] datetime NOT NULL,
[DateSample2] datetime NOT NULL
)
GO
INSERT dbo.TestTable (DateSample1, DateSample2)
VALUES('2006-10-06 00:00:00.000', '2007-01-17 00:00:00.000')
/*
In your select statement you should return another column "DateSample3"
and this should be year from DateSample1 and month and day from dateSample2
*/
--my try1
SELECT
tt.DateSample1, tt.DateSample2,
DateSample3 = CAST(DATEPART(YYYY, tt.DateSample1) AS CHAR(4))
+ CAST(DATEPART(MM, tt.DateSample2) AS CHAR(2))
+ CAST(DATEPART(dd, tt.DateSample2) AS CHAR(2))
,WantedResultForDateSample3='2006-01-17 00:00:00.000'
FROM
dbo.TestTable tt
--mytry2 THROWS AN ERROR
--Conversion failed when converting date and/or time from character string
/*
SELECT
tt.DateSample1, tt.DateSample2,
DateSample3 = CONVERT(DATETIME,CAST(DATEPART(YYYY, tt.DateSample1) AS CHAR(4))
+ CAST(DATEPART(MM, tt.DateSample2) AS CHAR(2))
+ CAST(DATEPART(dd, tt.DateSample2) AS CHAR(2)),120),
WantedResult='2006-01-17 00:00:00.000'
FROM
dbo.TestTable tt
*/
You can use DATETIMEFROMPARTS
DATETIMEFROMPARTS(YEAR(tt.DateSample1),
MONTH(tt.DateSample2),
DAY(tt.DateSample2),
0,0,0,0)
Which is a lot cleaner than constructing a string IMO.
Whichever method you use you might have to deal with impossible dates with this requirement. One approach is below
SELECT CASE WHEN month=2
AND day = 29
AND (yr % 4 != 0 OR (yr % 100 = 0 AND yr % 400 != 0))
THEN NULL
ELSE
DATETIMEFROMPARTS(yr,
month,
day,
0,0,0,0)
END
FROM [dbo].[TestTable] tt
CROSS APPLY (VALUES (YEAR(tt.DateSample1),
MONTH(tt.DateSample2),
DAY(tt.DateSample2))) V(yr, month, day)
SQL Fiddle

Create Unique Constraint based on Start Date and End Date

I created a unique constraint as below which is working fine. But I want to create a constraint where the productNumber between the two dates should be unique
ALTER TABLE [dbo].[Product] ADD CONSTRAINT U_Product UNIQUE ([ProductNumber],[StartDate],[EndDate])
Right now, it is taking the exact value in columns, but I want it between two dates. How can I do this ?
create function dbo.IsProductUnique (#ProductNumber int, #StartDate date, #EndDate date) returns bit as
begin
if exists (
select *
from Product
where ProductNumber = #ProductNumber
and StartDate < #EndDate
and EndDate > #StartDate) return 0
else
return 1 -- Unique
end
go
alter table Product add constraint CK_Product_Unique check (dbo.IsProductUnique(ProductNumber, StartDate, EndDate) = 1)
go

How to compare datetime in SQL Server in where clause

I have CreatedDate as datetime column in my database table. I want to fetch the rows where CreatedDate and current time difference is more than 1 hour
Select * from TableName where (DateDiff(hh,CreatedDate,GetDate())>1
Answer by #Amit Singh works if you only care about the hour value itself, versus any 60 minute period.
The problem with using DATEDIFF(hh) that way is that times of 13:01 and 14:59 are only one "hour" apart.
Like:
select datediff(hh,'1/1/2001 13:59','1/1/2001 14:01')
I think doing this would address that issue:
declare #cd datetime='9/12/2013 03:10';
declare #t table(id int,CreatedDate datetime);
insert #t select 1,'9/12/2013 02:50';
insert #t select 2,'9/12/2013 02:05';
select * from #t where #cd>(DateAdd(hh,1,CreatedDate))
Dan Bellandi raises a valid point, but if it really matters if the dates should be 60 minutes apart, then just check if they are 60 minutes apart:
SELECT * FROM TableName WHERE DATEDIFF(MINUTE, DateColumnName, GETDATE()) >= 60
If you don't expect any rows created in the future...
where CreatedDate < dateadd(hour, -1, getdate())
CREATE TABLE trialforDate
(
id INT NULL,
NAME VARCHAR(20) NULL,
addeddate DATETIME NULL
)
INSERT INTO trialforDate VALUES (1,'xxxx',GETDATE())
INSERT INTO trialforDate VALUES (2,'yyyy',GETDATE())
INSERT INTO trialforDate VALUES (1,'zzzz','2013-09-12 11:20:40.533')
SELECT *
FROM trialforDate
WHERE GETDATE() > DATEADD(HOUR, 1, addeddate)
C# Code
DateTime param1= System.DateTime.Now;
DateTime param2= System.DateTime.Now.AddHours(1);
SQL Query:
SELECT * FROM TableName WHERE CreatedDate = param1 AND CreatedDate =param2;

date comparison in sql server

I am trying to display records which have their date (I have a column Date in table) 30 days back from today's date. And once it gets displayed I need to make a new record by adding details with Date= today's date..
I tried this:
select * from
paymenthist
where
Date = CONVERT(datetime, CONVERT(varchar, DATEADD(day, -30, GETDATE()), 101))
But all records are getting displayed..
Ok, I admit the way I suggested may be inefficient, but if one is a datetime and the other is a date then I believe this will be more efficient than the >= <= approach because SQL is often not great at utilising indexes for queries like this, and under the covers a datetime is actually a floating point, so for pure efficiency, try this:
CREATE TABLE ##PaymentHistory
(
ID INT IDENTITY,
[Date] DATETIME,
Col1 INT,
Col2 INT
)
INSERT INTO ##PaymentHistory([Date],Col1,Col2)
VALUES(FLOOR(CAST(GETDATE() -29 AS FLOAT) ) ,1,1)
, (FLOOR(CAST(GETDATE() -30 AS FLOAT) ) ,2,2)
, (FLOOR(CAST(GETDATE() -31 AS FLOAT) ) ,3,3)
SET IDENTITY_INSERT ##PaymentHistory ON
INSERT INTO ##PaymentHistory(ID, [Date], Col1, Col2)
SELECT ID, GETDATE(), Col1, Col2
FROM ##PaymentHistory
WHERE CAST(Date AS FLOAT) = FLOOR(CAST(GETDATE() -30 AS FLOAT) )
SET IDENTITY_INSERT ##PaymentHistory OFF
It depends somewhat on the datatype of the date column, but try this.
select * from paymenthist where cast(Date as date) = cast(DATEADD(day, -30, GETDATE()) as date)

Resources