Date Extracted from datetime in sql server 2008 - sql

I have a column of DateTime and I give only the date to a stored procedure and check it against the column in SQL table. But entries in column also contains time with date but I have to compare the only date part of column with the given input. Please reply
alter procedure [dbo].[db]
#date DateTime
As
begin
select * from [dbo].[production_schedule]
where DATEPART('YYYY',date)= DATEPART('YYYY-MM-DD',#date)
end;
EXEC [dbo].[db] '2002-07-01',1,0
I have to give only date in the procedure but I have to select those rows which have the same date in the column date.

Try this
select * from [dbo].[production_schedule]
where convert(date,date)= convert(date,#date)

Write as:
alter procedure [dbo].[db]
#date DateTime
As
begin
select * from [dbo].[production_schedule]
where convert ( varchar(10), date, 111) = convert (varchar(10),#date,111)
end
Go
-- When there's only one input parameter in the sproc then why have 3 comma separated
-- inputs in exec statement?
EXEC [dbo].[db] '2002-07-01'
check demo here.

Related

Temporarily change format of a date column in SQL Query output MM/YY -> MM/DD/YYYY

I have data on my SQL Server that is formatted like so:
06/21
MM/YY
I would like to manipulate it so that all the dates are displayed as MM/DD/YYYY. So as the previous example it would look like:
06/01/2021
I was wondering if there is some sort of function that I can run in my query to display the date column differently in my output? I don't want to actually alter the way in which the Column is formatted on the back end, I just want to change how it is presented to the user in the results of a single query.
Thank you for your help!
Using STUFF
declare #var varchar(64) = '06/21 '
select stuff(#var,4,0,'01/20')
So for your table.
select stuff(yourColumn,4,0,'01/20')
From yourTable
Just replace / with 01/20:
declare #yourDate varchar(10) = '06/21'
select replace(#yourDate ,'/','/01/20')
Result:
But it is probably wiser to cast it to a proper date type:
declare #yourDate varchar(10) = '06/21'
select cast(replace(#yourDate ,'/','/01/20') as date)
you can use this solution
it works with all years 1998, .. 2000,2001 ...
declare #theDate varchar(10) = '06/21'
select convert(date,'01/'+ #theDate ,3)

Convert datetime and divide into 2 column in SQL server

I'm working in a SQL table which contains a column called 'DATETIME' and it contains values like '201701011730'. The first 8 character is the date and last 4 characters is the time. Now I need to create a column called 'TIME' and also a column called 'DATE' to replace 'DATETIME'. The example has shown below:
DATETIME(201701011730)--> DATE(20170101) and TIME(1730)
I'm trying to work with a update statement with CONVERT function but it doesn't worked. Is there any suggestion to work with?
Assuming your combined column is called dattimCol you can do the following:
select convert(date, left(dattimCol,8)) [date],
convert(time, stuff(substring(dattimCol,9,4),3,0,':')) [time]
from yourTable;
It is important to insert the ':' into the time-string before converting it.
As an update statement this transforms to:
update yourTable SET
dateCol=convert(date, left(dattimCol,8)),
timeCol=convert(time, stuff(substring(dattimCol,9,4),3,0,':'));
OK, here are some short explanations, first substring():
substring(dattimCol,9,4)
(I could have used right(dattimCol,4) instead) will get us the 4 last digits of the datetime string representing the time of day ("1730"). I then "stuff" a colon (":") in the middle of that resultant string by using the stuff() function (available since at least SQL-server 2005)
stuff( sourceString, beginInsertionAtPosition, countOfCharsToDelete, insertionString )
Try as follows:
CREATE TABLE DATES(DATETIME VARCHAR(20))
INSERT INTO DATES VALUES('201701011730')
INSERT INTO DATES VALUES('201801011740')
SELECT * FROM DATES
ALTER TABLE DATES ADD [DATE] VARCHAR(8)
ALTER TABLE DATES ADD [TIME] VARCHAR(4)
DECLARE #DATETIME VARCHAR(MAX)
DECLARE C CURSOR FOR
SELECT DATETIME FROM DATES
OPEN C
FETCH NEXT FROM C INTO #DATETIME
WHILE ##FETCH_STATUS=0
BEGIN
UPDATE DATES SET DATE=(SELECT SUBSTRING(DATETIME,0,9) FROM DATES WHERE DATETIME=#DATETIME) WHERE DATETIME=#DATETIME
UPDATE DATES SET TIME=(SELECT SUBSTRING(DATETIME,9,LEN(DATETIME)) FROM DATES WHERE DATETIME=#DATETIME) WHERE DATETIME=#DATETIME
FETCH NEXT FROM C INTO #DATETIME
END
CLOSE C
DEALLOCATE C
SELECT * FROM DATES
I have used the below code for showing the example you can use the below code
Create Table #ABC(T1 NVARCHAR(500),date nvarchar(255),Time nvarchar(255))
Insert Into #ABC(T1) Values ('201701011730')
Update #ABC
SET date=SUBSTRING(T1,0,9), Time=SUBSTRING(T1,9,LEN(t1))
I think you are using string format rather then date and time format for more information you can go to the following links
http://www.w3schools.com/sql/func_convert.asp
https://msdn.microsoft.com/en-us/library/ms187928.aspx
-----Declare #datetime_str variable where set datetime in string format
Declare #datetime_str varchar(20);
set #datetime_str='201701011730';
select SUBSTRING(#datetime_str,0,9) as date, SUBSTRING(#datetime_str,9,12) as time
--------------------or-------------------
select SUBSTRING('201701011730',0,9) as date, SUBSTRING('201701011730',9,12) as time

Convert date string to date sql server

I have a table tbl with column cln varchar(50).
Data is stored in format 'January-2008', February-2009, March-2010 etc(full month name)
I want to convert it to date (for comparison, sort etc).
please try below query
DECLARE #v varchar(20)
SET #v='January-2008'
SELECT CAST('01-'+#V as DATE)
Since you don't get the day data and only -, we'll add '01-' to complete the date day part.
sql fiddle link: http://sqlfiddle.com/#!6/6f326/7
Use Convert with Style to avoid errors in different date settings
DECLARE #v varchar(20)
SET #v='January-2008'
SELECT CONVERT(DATETIME,'01-'+#v,13)

How do I properly SELECT WHERE Effective_Date >= 'Given_Date' in a stored procedure?

I have this select statement that returns the results I'm looking for:
SELECT *
FROM Database.dbo.Table
WHERE Effective_Date >= '04/01/2014'
AND Chain = 'MCD'
I'm looking to turn this into a stored procedure with the following variables, #EffectiveDate and #Chain so that I can simply replace the date and chain to get different results. Here is the stored procedure I've made that doesn't work correctly:
CREATE PROCEDURE Database.dbo.StoredProc
#Chain VARCHAR(255),
#EffectiveDate VARCHAR(255)
AS
SELECT *
FROM Database.dbo.Table
WHERE Effective_Date >= '+#EffectiveDate+'
AND Chain = '+#Chain+'
GO
I'd like to execute this stored procedure like this:
EXEC Database.dbo.StoredProc
#PharmacyChain = N'MCD',
#EffectiveDate = N'04/01/2014'
;
GO
In this example, Table.Effective_Date is in datetime format. When I run the SELECT statement w/o the stored proc, the date comparison works fine to only select records with effective date after '04/01/2014'. However, when it's run using the variables int he stored proc, it doesn't convert the date correctly to compare. I've tried changing the EffectiveDate variable to datetime format, but still had no luck. Any help would be greatly appreciated. Thank you
Parameters should match the column datatype
#Chain VARCHAR(255) -- what is Chain?
#EffectiveDate datetime -- or date etc
And simply do this
SELECT *
FROM dbo.Table
WHERE Effective_Date >= #EffectiveDate
AND Chain = #Chain;
You don't need 3 part object names either

How to Update Column,whose datatype is DateTime

I have table named as dbo.SetCustomerRFMComData with eight columns.
In which the third column name is RecDatetime whose DataType is DATETIME
I update the table using an stored procedure.
How to add current Datetime in RecDateTime column while firing an UPDATE QUERY
In SQL Server use GETDATE() .
In MySQL and PostgreSQL , use NOW().
In Oracle , use SYSDATE.
Call GETDATE() method which will update you current date time
Suppose your sp looks like this
create procedure sp_proc
(
#RecTime Datetime
)
as
begin
set #RecTime =DateTime()
update tablename values(RecTime=#RecTime )
end