Date and Time fields combine to DateTime in SQL Server 2000? - tsql

I have 2 fields, Date and Time, which need to be combined into 1 datetime field. I've seen functions which do this, but they don't seem to work with my data.
Date char(8): 20051101
TIME char(4): 1115
Result needed: Date time representing Nov. 1st 2005, 11:15 am
How can I do this?

Assuming your data type is int, you can do:
declare #d as int
declare #t as int
set #d = 20051101
set #t = 1115
select CAST(cast(#d as varchar) as datetime) + dateadd(hh, cast(left(#t, 2) as int), 0) + dateadd(N, cast(right(#t, 2) as int), 0)
Updated for char:
declare #d as char(8)
declare #t as char(4)
set #d = '20051101'
set #t = '1115'
select CAST(#d as datetime) + dateadd(hh, cast(left(#t, 2) as int), 0) + dateadd(N, cast(right(#t, 2) as int), 0)

Related

SQL Setting Variable for Current Year Month by Combining two VarChar fields using case statement

I am trying to declare a variable for the current year and month based on a field called YEARMO.
It's a 6 character varchar field with the first 4 characters representing the year and the next 2 characters representing the month (ex. February 2018 as 201802).
I need the month variable to have a 0 in front of it if is a month that only has one digit (any month before October). Current code returns '20182' and would like it to return '201802'.
declare #current_month varchar(6)
set #current_month = CAST( year(getdate()) as varchar(4))
+ case when len(CAST( month(getdate()) as varchar(2))) < 1 then '0' +
CAST( month(getdate()) as varchar(2))
else CAST( month(getdate()) as varchar(2))
end
select #current_month;
You can use Convert function if you are looking for current month
select convert(char(6), getdate(), 112)
Your code is over complicated. Use right instead:
declare #current_month char(6)
set #current_month = CAST( year(getdate()) as varchar(4)) + right('00' + cast(month(getdate()) as varchar(2)), 2)
select #current_month;
Result:
201802
If you really want to use case instead, you should change the 1 to 2:
set #current_month = CAST( year(getdate()) as varchar(4)) +
case when len(CAST(month(getdate()) as varchar(2))) < 2 then
'0' + CAST( month(getdate()) as varchar(2)) else
CAST( month(getdate()) as varchar(2)) end
declare #current_month varchar(6)
set #current_month = CAST(year(getdate())*100 + month(getdate()) as varchar(6))

Adding Parameter causing issues-No data displayed

Hi all I have a stored procedure with two parameters #Startdate and #Enddate. When i execute the procedure i get data.
Now i added a parameter and it has list of values. So i added a split function and added in the WHERE clause. Now after making the changes when i execute my SP i do not get any data. I tried commenting out the 3rd Parameter from the WHERE clause and now i see the data again. Not sure what is happening. Any advice is greatly appreciated.
I have tried different split functions and Charindex(','+cast(tableid as varchar(8000))+',', #Ids) > 0 and nothing has worked.
Thanks
NOTE: The concatenation and splitting of parameter values is a poor design for performance reasons and, most importantly, very susceptible to SQL injection attacks. Please research some alternatives. If you must proceed down this path...
There are a great many split functions out there, but I used this one here to illustrate a possible solution.
CREATE FUNCTION [dbo].[fnSplitString]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (splitdata)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
GO
It's unclear, from your question, if you need to filter your results based on an int, varchar or various other data types available, but here are two options (and probably the most common).
DECLARE #TableOfData TABLE
(
ID_INT INT,
ID_VAR VARCHAR(100),
START_DATE DATETIME,
END_DATE DATETIME
)
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
DECLARE #Ids VARCHAR(1000)
DECLARE #Delimiter VARCHAR(1)
SET #Delimiter = ','
SET #StartDate = GETDATE()
SET #EndDate = DATEADD(HH, 1, GETDATE())
SET #Ids = '1,2,4'
--Create some test data
INSERT INTO #TableOfData
SELECT 1, '1', GETDATE(), DATEADD(MI, 1, GETDATE()) --In our window of expected results (date + id)
UNION SELECT 2, '2', GETDATE(), DATEADD(D, 1, GETDATE()) --NOT in our window of expected results b/c of date
UNION SELECT 3, '3', GETDATE(), DATEADD(MI,2, GETDATE()) --NOT in our expected results (id)
UNION SELECT 4, '4', GETDATE(), DATEADD(MI,4, GETDATE()) --In our window of expected results (date + id)
--If querying by string, expect 2 results
SELECT TD.*
FROM #TableOfData TD
INNER JOIN dbo.fnSplitString(#Ids, #Delimiter) SS
ON TD.ID_VAR = SS.splitdata
WHERE START_DATE >= #StartDate
AND END_DATE <= #EndDate
--If querying by int, expect 2 results
SELECT TD.*
FROM #TableOfData TD
INNER JOIN dbo.fnSplitString(#Ids, #Delimiter) SS
ON TD.ID_INT = CONVERT(int, SS.splitdata)
WHERE START_DATE >= #StartDate
AND END_DATE <= #EndDate
You cannot use a parameter with a list directly in your query filter. Try storing that separated data into a table variable or temp table and call that in your query or use dynamic SQL to write your query if you don't want to use table variable or temp tables.

T-SQL: Extract Substring

I have to read dates from a varchar column with the following possible patterns ( month/day/year ):
1/1/2005
1/13/2005
10/9/2005
10/13/2005
What is the correct way to read the day part of those dates with T-SQL?
Casting to date and using day() would be the correct approach imo:
declare #t table (string varchar(10))
insert #t values ('1/1/2005'),('1/13/2005'),('10/9/2005'),('10/13/2005')
select day(cast(string as date)) as the_day from #t
Would give:
the_day
-----------
1
13
9
13
An alternative if you want to avoid casting would be to use thesubstringandcharindexfunctions:
select
substring(
string,
charindex('/', string)+1,
charindex('/', string, charindex('/', string)+1)-charindex('/', string)-1
)
from #t

SQL query to count number of records within a given timeframe, filling in the gaps

I am trying to count the number of records that fall between a given time period, generally 15 minutes, but I'd like to have this interval a variable. My table has a datetime column and I need to get a count of the number of records for every 15 minute interval between two dates and when there aren't any records for the 15-minute window, I need that time period with a zero. I've tried using CTE in different combinations and couldn't get it to work. I can generate the date series using a CTE, but haven't been able to get the actual data in the result. I have a working solution using a stored procedure with a WHILE loop. I was hoping to avoid this if possible in favor or a more elegant solution.
Here is my working loop using a temporary table:
declare #record_count int = 0
declare #end_date_per_query datetime
create table #output (
SessionIdTime datetime,
CallCount int)
while #date_from < #date_to
begin
set #end_date_per_query = DATEADD(minute, #interval, #date_from)
select #record_count = COUNT(*) from tbl WHERE SessionIdTime between #date_from and #end_date_per_query
insert into #output values (#date_from, #record_count)
set #date_from = #end_date_per_query
end
select * from #output order by sessionIdTime
drop table #output
Hopefully someone can help with a more elegant solution. Any help is appreciated.
A CTE works just fine:
-- Parameters.
declare #Start as DateTime = '20120901'
declare #End as DateTime = '20120902'
declare #Interval as Time = '01:00:00.00' -- One hour. Change to 15 minutes.
select #Start as [Start], #End as [End], #Interval as [Interval]
-- Sample data.
declare #Sessions as Table ( SessionId Int Identity, SessionStart DateTime )
insert into #Sessions ( SessionStart ) values
( '20120831 12:15:07' ), ( '20120831 21:51:18' ),
( '20120901 12:15:07' ), ( '20120901 21:51:18' ),
( '20120902 12:15:07' ), ( '20120902 21:51:18' )
select * from #Sessions
-- Summary.
; with SampleWindows as (
select #Start as WindowStart, #Start + #Interval as WindowEnd
union all
select SW.WindowStart + #Interval, SW.WindowEnd + #Interval
from SampleWindows as SW
where SW.WindowEnd < #End
)
select SW.WindowStart, Count( S.SessionStart ) as [Sessions]
from SampleWindows as SW left outer join
#Sessions as S on SW.WindowStart <= S.SessionStart and S.SessionStart < SW.WindowEnd
group by SW.WindowStart
Is this what you're looking for?
-- setup
DECLARE #interval INT, #start DATETIME
SELECT #interval = 15, #start = '1/1/2000 0:00:00'
DECLARE #t TABLE (id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, d DATETIME)
INSERT INTO #t (d) VALUES
(DATEADD(mi, #interval * 0.00, #start)) -- in
,(DATEADD(mi, #interval * 0.75, #start)) -- in
,(DATEADD(mi, #interval * 1.50, #start)) -- out
-- query
DECLARE #result INT
SELECT #result = COUNT(*) FROM #t
WHERE d BETWEEN #start AND DATEADD(mi, #interval, #start)
-- result
PRINT #result

Cursor never ending in T-SQL

I have problems with a cursur that’s ends randomly. I want to produce a row for each element , so for every element there is a row for every month in 2012. If there is a row missing for a specific month, it should create that as well.
Now, it’s producing a row for the last element in every month until year 2057.
Now, I have a row for each element until in every month until year 2057 and only for one element in my table.
My table design:
create table tblDataUpdateTest
(
slno int identity(1,1),
cName varchar(50),
cRemarks varchar(50),
[Date] date,
)
insert into tblDataUpdateTest (cName, cRemarks,[Date]) values ('name1','Text1','2012-01-01'),
('name2','Text2','2012-01-01')
My code:
declare #y as int
declare #d as int
SET #y = 2012
SET #d = 1
Declare ##counter int
Declare ##month int
set ##counter=0
Declare ##slno int
Declare ##cRemarks varchar(100)
Declare ##cName varchar(50)
Declare ##Date date
set ##month = 1
Declare tmepTbl cursor
For
Select slno,cName,cRemarks,date from tblDataUpdateTest
Open tmepTbl /* Opening the cursor */
fetch next from tmepTbl
into ##slno,##cName,##cRemarks,##Date
while ##fetch_Status=-1
begin
if not exists (select cRemarks from tblDataUpdateTest where MONTH(Date) = ##month AND YEAR(Date) = 2012)
begin
insert into tblDataUpdateTest (cName, cRemarks,[Date]) values (##cName,'s',(DateAdd(yy, 2012-1900,DateAdd(m, ##month - 1, 01 - 1))))
end
fetch next from tmepTbl
into ##slno,##cName,##cRemarks,##Date
set ##month=##month+1
end
close tmepTbl
Deallocate tmepTbl
My table now
cName cRemarks Date
name1 Text1 2012-01-01
name2 Text2 2012-01-01
I want follwing to happen:
cName cRemarks Date
name1 Text1 2012-01-01
name1 Text1 2012-02-01
name1 Text1 2012-03-01
name2 Text2 2012-01-01
name2 Text2 2012-02-01
name2 Text2 2012-03-01
and so on.
Thanks!
Wouldn't be better to use a recursive CTE, instead of a cursor?
Here is an example:
DECLARE #y INT
DECLARE #m INT
DECLARE #n INT
SET #y = 2012
SET #m = 1
SET #n = 3
;WITH dates(d, m) AS(
SELECT CONVERT(DATE, CONVERT(VARCHAR(4), #y) + '-01-01'), 1
UNION ALL
SELECT CONVERT(DATE, CONVERT(VARCHAR(4), #y) + '-' + CASE WHEN m + 1 < 10 THEN '0' ELSE '' END + CONVERT(VARCHAR(2), m + 1) + '-01')
, m + 1
FROM dates
WHERE m < #n
)
INSERT INTO tblDataUpdateTest(cName, cRemarks,[Date])
SELECT cName, cRemarks, [date] FROM (
SELECT cName, cRemarks, dates.d AS [date]
FROM tblDataUpdateTest
CROSS JOIN dates) t
WHERE NOT(EXISTS(SELECT * FROM tblDataUpdateTest WHERE cName = t.cName AND [date] = t.[date]))
OPTION(MAXRECURSION 11)
SELECT * FROM tblDataUpdateTest ORDER BY cName