Convert and Insert varchar date from one table to another - sql-server

I want to insert date from one table to another. But the problem is, source table is having date stored as varchar and destination as date datatype.
Also I want to change the format of the date while inserting to destination.
Table1
Date varchar(80) null
Table2
Date Date null
Date in Table1 is stored in mm-dd-yyyy
I want to convert it into dd.mm.yyy and store it into Table2.
How should I convert it?
I tried below, but its not working.
select CONVERT(VARCHAR(10),TRY_Convert(date,[Date]),104)

If your destination table has a date field of date type all you should do is to convert your source data to date type and insert it.
The format dd.mm.yyyy that you want as output is NOT date format but a string and you can always get your date data from the second table using convert to string with the format 104 while selecting data from your second table like this:
declare #Table1 table ([Date] varchar(80) null);
insert into #Table1 values ('12-31-2001'), ('02-28-2002');
declare #Table2 table ([Date] Date null);
insert into #Table2
select convert(date, [date], 101)
from #Table1;
select convert(char(10), [date], 104)
from #Table2;
Here I used table variables and you should use your Table1, Table2 instead

Assuming style 104 is what you want, you just need one convert():
select TRY_CONVERT(VARCHAR(10), [Date], 104)
Your question is confusing because you specify that the source is a varchar and the destination a date. That would imply:
select TRY_CONVERT(DATE, [Date], 104)
I would also fix the table with the varchar "date" column so it uses the date data type. That is the right way to store dates. If you are going to store them as strings (which is occasionally necessary), then use YYYY-MM-DD format. This is (almost totally) unambiguous and easily turned back into a date.

Related

SQL Server - Add results of a SELECT query to an existing table

I currently have a table in SQL Server called masterTable. What I'd like to do is to add a new column to this table called report_Date.
I would like to store the results of a SELECT query in the report_Date column. The query works fine (it converts a nvarchar into a desired date format). What I can't do is append the results to the column.
My query:
SELECT
CONVERT(varchar(10), CAST(FileName AS date), 103) AS FileName
FROM dbo.masterTable
Any suggestions please?
If I understand your question correctly then
UPDATE dbo.masterTable SET
report_Date = CONVERT(varchar(10), CAST(FileName as date), 103)

List all dates within date range in SQL but ignore bank holidays

I'm making a holiday manager.
I have a table with a list of start and end dates for each instance of holiday.
[LeaveID], [EmployeeID], [StartDate], [EndDate]
I also do have a calendar table with dates from 2016-2030, listing the usual variations of date format as well as times the factory is shut, including bank holidays, etc.
I'm working on the front end for it now they want me to display it in sort of calendar format so I will need to mark on each day, who has booked time off.
I figure I need to list each date within each date range (start date to end date), then check if each date on the calendar appears on that list.
So basically I need to get a list of dates within a date range.
On top of that. I'd like to be able to compare the list of dates from above, to the calendar table so I can ignore bank holidays when calculating the amount of holiday used for each instance.
Thanks in advance!
To get a list of date within a date range, you will need source of numbers from 1 to n. I usually create such table and call it Numbers table.
To generate a list of date within a range, use following query.
SELECT
DATEADD(DAY, Numbers.Number-1, [StartDate]) Date
FROM
Numbers
WHERE
DATEADD(DAY, Numbers.Number-1, [StartDate]) <= [EndDate]
To create such table, refer to this question.
If you want to list all dates in Employee table, just cross join it.
SELECT
e.EmployeeID,
DATEADD(DAY, n.Number-1, e.[StartDate]) Date
FROM
Numbers n, Employee e
WHERE
DATEADD(DAY, n.Number-1, e.[StartDate]) <= e.[EndDate]
As you already have a dates table, you do not need the numbers table mentioned in the other answer. To accomplish what you are after requires a simple SQL Join from your dates table. Depending on how you want to format your final report you can either count up the number of EmployeeIDs returned or group them all into a calendar/table control in your front end on the DateValue.
In the query below you will get at least one DateValue for every date specified in the range (for which you can apply your own filtering such as where Dates.BankHoliday = 0 etc) and more than one where multiple Employees have taken leave:
-- Build some dummy data to run the query against.
declare #Emp table (LeaveID int, EmployeeID int , StartDate datetime, EndDate datetime);
insert into #Emp values
(1,1,'20161101','20161105')
,(2,1,'20161121','20161124')
,(3,2,'20161107','20161109')
,(4,3,'20161118','20161122');
declare #Dates table (DateKey int, DateValue datetime, DateLabel nvarchar(50));
declare #s datetime = '20161025';
with cte as
(
select cast(convert(nvarchar(8),#s,112) as int) as DateKey
,#s as DateValue
,convert(nvarchar(50),#s,103) as DateLabel
union all
select cast(convert(nvarchar(8),DateValue+1,112) as int)
,DateValue+1
,convert(nvarchar(50),DateValue+1,103)
from cte
where DateValue+1 <= '20161205'
)
insert into #Dates
select * from cte;
-- Actually query the data.
-- Define the start and end of your date range to return.
declare #MinStart datetime = (select min(StartDate) from #Emp);
declare #MaxEnd datetime = (select max(EndDate) from #Emp);
select d.DateValue
,e.EmployeeID
from #Dates d
left join #Emp e
on(d.DateValue between e.StartDate and e.EndDate)
where d.DateValue between #MinStart and #MaxEnd
order by d.DateValue
,e.EmployeeID;

SQL Server : convert datetime in place in table

Basically I inherited a rather large table which has a few columns with dates formatted as varchar(10) of '##.##.####' (day.month.year). I would like to convert these columns to Datetime columns for that specific date.
Is there anyway to convert these in place on SQL Server (through a single set of SQL queries), instead of SELECTing each record in some programming language, converting the date and then UPDATEing back as Datetime (perhaps to a different column)?
There is no need in ...=(select...) The action is simple and straightforward.
ALTER TABLE YourTable
ADD NewDateColumn DATETIME
update YourTable set NewDateColumn = convert(date, OldDateColumn, 104)
--Magic 104 is for dd.MM.yyyy date format
That's all.
How about this as an alternative to Jim's comment. First add new DATE column:
ALTER TABLE YourTable
ADD NewDateColumn DATETIME
Then to UPDATE (I suppose you would want to use the same standard you've been using):
UPDATE t
SET t.NewDateColumn = (SELECT CONVERT(DATE, OldDateColumn, 104)
FROM YourTable ta WHERE t.ID = ta.ID)
FROM YourTable t
For someone that might want to get it from the German standard to the U.S. standard:
UPDATE t
SET t.NewDateColumn = (SELECT CONVERT(DATETIME,
CONVERT(DATE, OldDateColumn, 104)
,101)
FROM YourTable ta WHERE t.ID = ta.ID)
FROM YourTable t
This is assuming you do have an ID column.

Custom autogenerated ID in sql server

How can I create a custom auto-generated ID in this format:
yyyymmdd-xxxxx
where:
yyyymmdd is the present date and
xxxxx is an auto increment integer number starting from 0
and the next day xxxxx should be restarted to 0.
Thanks
Create one autonumeric ID column in your db
save the date/time of each insert row.
Then use a ROW_NUMBER() function
SELECT *,
dayField + '-' + CAST(rn AS VARCHAR(100))
FROM (
SELECT ID, dateTimeField,
-- truncate the time and convert to yyyymmdd
CONVERT(VARCHAR(10), cast(dateField As Date), 112) as dayField,
ROW_NUMBER() OVER (PARITION BY cast(dateField As Date)
ORDER BY dateTimeField) as rn
-- or just ORDER BY ID
) T
Now if you want save this on the db, you probably will need a trigger.
You might consider including an Identity column and a datetime column that will be set on insert and than add a calculated column to put the two together.

SQL Select for create daily log data from more than one date column frrom a single table

I have a table with more than one date column,
each date column hold a date or null value,
I want to write a SQL query which will display each column have date into a new row with a new additional column named LogDate that contain the same date of column.
Its difficult to explain, please referrer the attached image.
Just use UNION ALL to concatenate the three result sets:
SELECT [ReceivedDate] AS LogDate, * FROM MyTable WHERE [ReceivedDate] IS NOT NULL
UNION ALL
SELECT [Closing Date] AS LogDate, * FROM MyTable WHERE [Closing Date] IS NOT NULL
UNION ALL
SELECT [LPODate] AS LogDate, * FROM MyTable WHERE [LPODate] IS NOT NULL
To sort by LogDate simply add the following ORDER BY clause to the end of this query:
ORDER BY LogDate

Resources