5 new entries for every existing row - sql

date, product, new_col,
2013/05/16, A,
2013/05/18, A,
2013/06/15, A,
2013/05/16, B,
2013/06/13, B,
2013/06/20, B
I am using SQL Server 2008.
For every existing entry, in new_col I need to store into new_col 5 previous calendar dates up to and including the date in the date column. E.g. for the 1st row in the above table, I need 5/16,5/15,5/14,5/13,5/12 in the new_col.
I have a lot of products in the table and a lot of dates for every product.
I have tried to partition the table based on these two columns but can't figure out a way to enter 5 days in the new_col.
Please help with any suggestions to do this.

WITH cal AS (
SELECT CAST('20130101' AS DATE) as cal_date
UNION ALL
SELECT DATEADD(day, 1, cal_date)
FROm cal
WHERE cal_date < CAST('20131231' AS DATE )
)
SELECT
[date],[product],
new_col = STUFF((SELECT ',' + CONVERT(VARCHAR(10),cal.cal_date,111)
FROM cal
WHERE cal.cal_date BETWEEN DATEADD(day, -4, tbl.[date]) AND tbl.[date]
ORDER BY cal.cal_date DESC
FOR XML PATH('')
),1,1,'')
FROM tbl
OPTION (maxrecursion 0)
sql fiddle demo

I don't know if this is the best solution but it's the first that popped into my head. Also as people have been mentioning, you do not need to store this... you can call this function directly from whatever reporting solution you've deployed. Was lazy about removing the last comma but that's pretty simple. Also feel free to adjust the datetime formatting as you see fit.
CREATE TABLE dbo.Sam ([Date] DATE, Product VARCHAR(10), NewCol VARCHAR(1000))
INSERT INTO dbo.Sam
SELECT '2013/05/16','A',NULL
UNION ALL SELECT '2013/05/18','A',NULL
UNION ALL SELECT '2013/06/15','A',NULL
UNION ALL SELECT '2013/05/16','B',NULL
UNION ALL SELECT '2013/06/13','B',NULL
UNION ALL SELECT '2013/06/20','B',NULL
GO
CREATE FUNCTION dbo.fnGet4PreviousDates(#Date DATE, #Product VARCHAR(10))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE #Out VARCHAR(1000) = ''
SELECT #Out = #Out + CONVERT(VARCHAR,[Date],112) + ','
FROM (
SELECT TOP 5 [Date]
FROM dbo.Sam
WHERE Product = #Product
AND [Date] < #Date
ORDER BY [Date] DESC
) t
RETURN #Out
END
GO
UPDATE dbo.Sam
SET NewCol = dbo.fnGet4PreviousDates([Date],Product)
SELECT * FROM dbo.Sam

Related

Incorrect Syntax near With

No matter where I place my With statement inside the SQL query, the keyword in the next line always shows an error, 'Incorrect syntax near keyword'. I also tried putting semi-colon.
; WITH Commercial_subset AS
(
SELECT DISTINCT
PRDID_Clean, Value, [Year]
FROM
Reporting_db_SPKPI.DBO.[tbl_RCCP_commercial]
WHERE
MEASURE = 'Unit Growth Rate'
)
--error appears at truncate
TRUNCATE TABLE Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_dup]
Example 1:
[Example 1][1]
Example 2:
[Example 2][2]
What am I missing?
[1]: https://i.stack.imgur.com/lkfVd.png
[2]: https://i.stack.imgur.com/tZRnG.png
My Final code after getting suggestions in the comments,
--Ensure the correct database is selected for creating the views
USE Reporting_db_SPKPI
--Create the table where new values will be appended
Insert into Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_dup]
Select *, Replace(productID,'-','') as ProductID_clean from Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR]
GO
--Create a subset as view which will be used for join later
Create or Alter View QRY_Commerical_Subset AS
Select Distinct PRDID_Clean, Value, [Year] From Reporting_db_SPKPI.DBO.[tbl_RCCP_commercial] where MEASURE = 'Unit Growth Rate'
Go
--Create a view with distinct list of all SKUs
CREATE OR ALTER VIEW QRY_RCCP_TEMP AS
SELECT
PRODUCTID, ROW_NUMBER() Over (ORDER BY ProductID) AS ID
FROM (
SELECT
DISTINCT A.ProductID_clean ProductID
FROM
Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_dup] A
LEFT JOIN
Reporting_db_SPKPI.DBO.QRY_Commerical_Subset B ON A.ProductID_clean = B.PRDID_Clean
WHERE
B.PRDID_Clean IS NOT NULL --and A.filename = 'Capacity Planning_INS_Springhill' --DYNAMIC VARIABLE HERE
and Cast(A.SnapshotDate as date) =
(SELECT Max(Cast(SnapshotDate as date)) FROM reporting_db_spkpi.dbo.tbl_RCCP_3_NR)
) T
GO
SET NOCOUNT ON
-- For every product id from the distinct list iterate the following the code
DECLARE #I INT = 1
WHILE #I <= (SELECT MAX(ID) FROM QRY_RCCP_TEMP)
BEGIN
DECLARE #PRODUCT NVARCHAR(50) = (SELECT PRODUCTID FROM QRY_RCCP_TEMP WHERE ID = #I)
DROP TABLE Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_temp]
--Retrieve last 12 months of value from NR and add it to a temp table in increasing order of their months. These 12 data points will be baseline
SELECT
Top 12 A.*,
Case When B.[Value] is Null then 0 else CAST(B.[Value] as float) End GROWTH
INTO
Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_temp]
FROM
Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_dup] A
LEFT JOIN
--using the view here
QRY_Commerical_Subset B ON B.PRDID_Clean = A.ProductID_clean AND B.[YEAR] = YEAR(A.[MONTH])+1
WHERE
A.PRODUCTID= #PRODUCT
AND Cast(A.SnapshotDate AS DATE) = (SELECT Max(Cast(SnapshotDate AS DATE)) FROM reporting_db_spkpi.dbo.[tbl_RCCP_3_NR_dup])
Order by
[Month] desc
-- Generate 3 years of data
DECLARE #J INT = 1
WHILE #J<=3
BEGIN
--Calculate next year's value
UPDATE Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_temp]
SET
[Value] = [Value]*(1+ GROWTH),
[MONTH] = DATEADD(YEAR,1,[Month]),
MonthCode= 'F' + CAST(CAST(SUBSTRING(MonthCode,2,LEN(MonthCode)) AS INT) + 12 AS NVARCHAR(10))
--Add it to the NR table.
Insert into Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_dup]
(ProductID, MonthCode, Value, Month, FileName,
LastModifiedDate, SnapshotDate, Quarter, IsError, ErrorDescription)
Select
ProductID, MonthCode, Value, Month, FileName,
LastModifiedDate, SnapshotDate, Quarter, IsError, ErrorDescription
from
Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_temp]
--Update growth rate for next year
UPDATE Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_temp]
SET GROWTH = Case When B.[Value] is Null then 0 else CAST(B.[Value] as float) End
FROM Reporting_db_SPKPI.DBO.QRY_Commerical_Subset B
WHERE B.PRDID_Clean = ProductID_clean AND [YEAR] = YEAR([MONTH])+1
SET #J=#J+1
END
SET #I=#I+1
END
DROP VIEW QRY_RCCP_TEMP
DROP VIEW QRY_Commerical_Subset
The WITH is a Common Table Expression, aka CTE.
And a CTE is like a template for a sub-query.
For example this join of the same sub-query:
SELECT *
FROM (
select distinct bar
from table1
where foo = 'baz'
) AS foo1
JOIN (
select distinct bar
from table1
where foo = 'baz'
) AS foo2
ON foo1.bar > foo2.bar
Can be written as
WITH CTE_FOO AS (
select distinct bar
from table1
where foo = 'baz'
)
SELECT *
FROM CTE_FOO AS foo1
JOIN CTE_FOO AS foo2
ON foo1.bar > foo2.bar
It's meant to be used with a SELECT.
Not with a TRUNCATE TABLE or DROP TABLE.
(It can be used with an UPDATE though)
As such, treat the TRUNCATE as a seperate statement.
TRUNCATE TABLE Reporting_db_SPKPI.DBO.[tbl_RCCP_3_NR_dup];
WITH Commercial_subset AS
(
SELECT DISTINCT
PRDID_Clean, Value, [Year]
FROM
Reporting_db_SPKPI.DBO.[tbl_RCCP_commercial]
WHERE
MEASURE = 'Unit Growth Rate'
)
SELECT *
FROM Commercial_subset;
Btw, the reason why many write a CTE with a leading ; is because the WITH clause raises an error if the previous statement wasn't ended with a ;. It's just a small trick to avoid that error.

Returning the following season and year

For a particular season and year when it started I have to get the following season and year when it starts, e.g. for Summer 2021 I should get Autumn 2021, and for Winter 2021 I should get Spring 2022.
"Seasons" table has the "Order" column which indicates the order of seasons in a year, so it looks like this:
SeasonID
Order
Name
1
1
Spring
2
2
Summer
3
3
Autumn
4
4
Winter
Remark: "Order" column may seem redundant, but this is actually simplified/adapted version of the problem I have, where "Order" column is neccesary.
I have a stored procedure that has #Year and #SeasonID as input parameters. I have to get following season/year in #FollowingSeasonID and #FollowingYear parameters, which I use later in the stored procedure. I'm not sure if I've used the best technique for that:
(...)
DECLARE #FollowingSeasonID int;
DECLARE #FollowingYear int;
if object_id('tempdb..#Years') is not null drop table #Years
CREATE TABLE #Years ([Year] int)
INSERT INTO #Years ([Year]) VALUES (#Year), (#Year + 1)
SELECT #FollowingSeasonID = FollowingSeasonID, #FollowingYear = FollowingYear
FROM
(SELECT SeasonID,
[Year],
LEAD(SeasonID) OVER (ORDER BY [Year], Order) AS FollowingSeasonID,
LEAD([Year]) OVER (ORDER BY [Year], Order) AS FollowingYear
FROM Seasons
CROSS JOIN #Years) t
WHERE SeasonID = #SeasonID AND [Year] = #Year
(...)
Is there a better way to do that? Could it be achieved in just one query?
I need those values in multiple stored procedures/views/... so I wanted to extract that part of code if a function. Scalar valued function can't return two values, so I have to create a table valued function (and I have to use table variable instead of temp table #Years). However, is there a better way to do that instead of having a table valued function that always returns just one row?
You can wrap this code in UDF and you should be able to get seasonId, year
DECLARE #season table(SeasonId int, SeasonOrder int, Name varchar(10))
INSERT INTo #season values
(1, 1 ,'Spring')
,(2, 2 ,'Summer')
,(3, 3 ,'Autumn')
,(4, 4 ,'Winter');
DECLARE #FollowingSeasonID int;
DECLARE #FollowingYear int;
DECLARE #year int = 2021, #SeasonId int = 2;
;WITH CTE_YearSeason AS
(
SELECT y,s.* FROM #season as s
CROSS APPLY
(VALUES (#year), (#year+1)
) as t(y)
), cte_ranking as
(
SELECT *, row_number() over (order by y,SeasonOrder) as rnk
FROM CTE_YearSeason)
SELECT SeasonId, Y as year
FROM cte_ranking as c
where c.rnk = (SELECT c1.rnk
from cte_ranking as c1
where c1.SeasonId = #SeasonId and c1.y = #year) +1
SeasonId
year
3
2021
Unless I've misunderstood, given a single seasonId you just need the following Id and reset it to 1 and increment the year if necessary?
declare #seasonid int=1, #Year int=2021
select FollowingSeasonID, #Year + yr FollowingYear
from (
select *,
IsNull(Lead(SeasonId) over(order by [order]),1) FollowingSeasonID,
case when Lead(SeasonId) over(order by [order]) is null then 1 else 0 end yr
from seasons
)s
where SeasonId=#SeasonId
If you don't want to use a TVF you could just use this as a view/cte, joining on currentId and return the followingId and yr value to add to your current year.

SQL Query - gather data based on date range - possible variable number of columns

please forgive my inexperience, I hope this isn't too dumb of a question, I'm stuck and have no where else to turn. I'll keep it to the point:
I'm trying to gather payroll data with the results like so:
The issue I have is the variable number of columns. I will be given a date range and are required to return an attendance record for each day in the given range, or a null value if no data is present. I'm using WebAPI as middle tier so I have the ability to perform further data manipulation to achieve this result.
My tables are as follows:
I can't be the first person who needs this done, any articles/posts or anything that would help me accomplish this? Even pseudo code would help; anything!
Thanks a million in advnace!
This is what I've been able to come up with but I'm not even sure if its doable:
-- convert date range into days of month
-- to ensure null values are included in data??
DECLARE #intFlag INT = 0;
DECLARE #numberOfDays INT = DATEDIFF(DAY, #startDate, #endDate);
DECLARE #TMP TABLE (DaysOfMonth date)
WHILE (#intFlag <= #numberOfDays)
BEGIN
INSERT INTO #TMP VALUES (DATEADD(DAY, #intFlag, #startDate));
SET #intFlag = #intFlag + 1
END
-- select days in given data range so c# app can build header row
-- would it help if I pivot this data?
SELECT
DaysOfMonth
FROM
#TMP
ORDER BY
DaysOfMonth
-- get a count for number of people
DECLARE #count INT = 0;
DECLARE #TMPPPL TABLE (Id int identity(1,0), PId Int)
INSERT INTO
#TMPPPL
SELECT
p.PersonId
FROM
dbo.People p
JOIN
dbo.UserTypes ut on p.UserType_UserTypeId = ut.UserTypeId and (ut.Code = 'caregiver' or ut.Code = 'director')
DECLARE #numberOfPeople INT = (SELECT COUNT(1) FROM #TMPPPL)
-- create and execute sproc to return row of data for each person
WHILE (#count <= #numberOfPeople)
BEGIN
-- STUCK HERE, This obviously won't work but what else can I do?
EXEC GetPersonAttendanceHours #personId, #startDate, #endDate;
SET #count = #count + 1
END
This was interesting. I think this will do what you're looking for. First test data:
CREATE TABLE people (PersonID int, Name varchar(30))
INSERT INTO people (PersonID, Name)
SELECT 1, 'Kelly'
UNION ALL SELECT 2, 'Dave'
UNION ALL SELECT 3, 'Mike'
CREATE TABLE attendances (PersonID int, SignIn datetime, SignOut datetime)
INSERT INTO attendances (PersonID, SignIn, SignOut)
SELECT 1, '1-Feb-2015 08:00', '1-Feb-2015 09:00'
UNION ALL SELECT 1, '1-Feb-2015 12:00', '1-Feb-2015 12:30'
UNION ALL SELECT 2, '2-Feb-2015 08:00', '2-Feb-2015 08:15'
UNION ALL SELECT 1, '3-Feb-2015 08:00', '3-Feb-2015 09:00'
UNION ALL SELECT 1, '4-Feb-2015 08:00', '4-Feb-2015 08:30'
UNION ALL SELECT 2, '4-Feb-2015 08:00', '4-Feb-2015 10:00'
UNION ALL SELECT 2, '6-Feb-2015 12:00', '6-Feb-2015 15:00'
UNION ALL SELECT 3, '6-Feb-2015 15:00', '6-Feb-2015 17:00'
UNION ALL SELECT 3, '8-Feb-2015 10:00', '8-Feb-2015 12:00'
Then a dynamic query:
DECLARE #startDate DATETIME='1-Feb-2015'
DECLARE #endDate DATETIME='9-Feb-2015'
DECLARE #numberOfDays INT = DATEDIFF(DAY, #startDate, #endDate)
declare #dayColumns TABLE (delta int, colName varchar(12))
-- Produce 1 row for each day in the report. Note that this is limited by the
-- number of objects in sysobjects (which is about 2000 so it's a high limit)
-- Each row contains a delta date offset, #startDate+delta gives each date to report
-- which is converted to a valid SQL column name in the format colYYYYMMDD
INSERT INTO #dayColumns (delta, colName)
SELECT delta, 'col'+CONVERT(varchar(12),DATEADD(day,delta,#startDate),112) as colName from (
select (ROW_NUMBER() OVER (ORDER BY sysobjects.id))-1 as delta FROM sysobjects
) daysAhead
WHERE delta<=#numberOfDays
-- Create a comma seperated list of columns to report
DECLARE #cols AS NVARCHAR(MAX)= ''
SELECT #cols=CASE WHEN #cols='' THEN #cols ELSE #cols+',' END + colName FROM #dayColumns ORDER BY delta
DECLARE #totalHours AS NVARCHAR(MAX)= ''
SELECT #totalHours=CASE WHEN #totalHours='' THEN '' ELSE #totalHours+' + ' END + 'ISNULL(' + colName +',0)' FROM #dayColumns ORDER BY delta
-- Produce a SQL statement which outputs a variable number of pivoted columns
DECLARE #query AS NVARCHAR(MAX)
SELECT #query=
'declare #days TABLE (reportDay date, colName varchar(12))
INSERT INTO #days (reportDay, colName)
SELECT DATEADD(day,Delta,'''+CONVERT(varchar(22),#startDate,121)+'''), ''col''+CONVERT(varchar(12),DATEADD(day,delta,'''+CONVERT(varchar(22),#startDate,121)+'''),112) as colName from (
select (ROW_NUMBER() OVER (ORDER BY sysobjects.id))-1 as Delta FROM sysobjects
) daysAhead
WHERE Delta<='+CAST(#numberOfDays as varchar(10))+'
SELECT p.Name, pivotedAttendance.*,'+#totalHours+' as totalHours FROM (
SELECT * FROM (
select p.PersonID, d.colName, CAST(DATEDIFF(MINUTE, a.SignIn, a.SignOut)/60.0 as decimal(5,1)) as hrsAttendance
from #days d
CROSS JOIN people p
LEFT OUTER JOIN attendances a ON a.PersonID=p.PersonID AND CAST(a.SignOut as DATE)=d.reportDay
) as s
PIVOT (
SUM(hrsAttendance) FOR colName in ('+#cols+')
) as pa
) as pivotedAttendance
INNER JOIN people p on p.PersonID=pivotedAttendance.PersonID'
-- Run the query
EXEC (#query)
Which produces data in a similar format to your example, with all of the days in the report range and a row for each person. From the above I see:
For presentation purposes you should be able to convert the column name to a display-able date (just parse the YYYYMMDD out of the column name). The date can't be used as the column name directly as it produces an invalid column name.
SQL Fiddle example here.
This is a variation on a theme that I've done in order to display schedules or attendance. I expect something similar should work with your report. Here is the beginning of your stored procedure:
DECLARE #iDay INT = 0;
DECLARE #countDays INT = DATEDIFF(DAY, #startDate, #endDate);
DECLARE #tempDates TABLE ([tempDate] DATE);
DECLARE #filterDates NVARCHAR;
WHILE (#iDay <= #countDays)
BEGIN
INSERT INTO #tempDates VALUES (DATEADD(DAY, #iDay, #startDate));
SET #iDay = #iDay + 1;
END;
SELECT #filterDates = STUFF(
(SELECT N''',''' + CONVERT(NVARCHAR, [tempDate], 103) FROM #tempDates FOR XML PATH('')),
1,
2,
''
);
You were on the right track with your suggestion. The next query gets your data before you PIVOT it.
SELECT [People].[Person_PersonID], [tempDates].[tempDate], [Attendances].[SignIn], [Attendances].[SignOut],
MIN([Attendances].[SignOut], DATEADD(DAY, 1, [tempDates].[tempDate]))
- MAX([Attendances].[SignIn], [tempDates].[tempDate]) * 24 AS [numHours]
FROM [People]
CROSS JOIN #tempDates [tempDates]
LEFT JOIN [Attendances]
ON (
([Attendances].[SignIn] < DATEADD(DAY, 1, [tempDates].[tempDate]))
AND ([Attendances].[SignOut] > [tempDates].[tempDate])
);
Once we're satisfied with the results of the previous query, we substitute it with a query using PIVOT, which should look something like this.
SELECT *
FROM (
SELECT [People].[PersonID], [tempDates].[tempDate], [Attendances].[SignIn], [Attendances].[SignOut],
MIN([Attendances].[SignOut], DATEADD(DAY, 1, [tempDates].[tempDate]))
- MAX([Attendances].[SignIn], [tempDates].[tempDate]) * 24 AS [numHours]
FROM [People]
CROSS JOIN #tempDates [tempDates]
LEFT JOIN [Attendances]
ON (
([Attendances].[SignIn] < DATEADD(DAY, 1, [tempDates].[tempDate]))
AND ([Attendances].[SignOut] > [tempDates].[tempDate])
)
) AS [DatedAttendance]
PIVOT (
SUM([numHours]) FOR ([tempDate] IN (#filterDates))
) AS [PivotAttendance]
ORDER BY [PersonID]

Sql query to find the Most starting characters

Simplified scenario, I have a table with the following fields/values:
ID value
1 '12345'
2 '1234'
3 '123'
4 '12'
5 '1'
I want to find the record that is the closest to A='1230' and it should correspond to ID=3.
The only implementation I have in mind now is basic... Use a loop to iterate through A substring and do the comparison.
Is there a better way to solve this?
Will appreciate your help
Try this :-
Declare #valueToSearch int
Set #valueToSearch =1230
;WITH cte
AS
(
SELECT ID,RANK() OVER(ORDER BY ABS(value-#valueToSearch)) AS num FROM Sample
)
SELECT ID FROM cte
WHERE num=(SELECT MIN(num) FROM cte
This will give 2 as the result
Sql Fiddle
declare #q varchar(5)
select #q = '1230'
select top 1 number, substring(source.value, 1, number)
from master.dbo.spt_values, source
where type='p'
and number<=len(source.value)
and substring(source.value, 1, number) = substring(#q, 1, number)
order by number desc
Or using like...
select top 1 * from #source s
where #q like value +'%'
order by len(value) desc

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

I have a MS SQL CTE query from which I want to create a temporary table. I am not sure how to do it as it gives an Invalid Object name error.
Below is the whole query for reference
SELECT * INTO TEMPBLOCKEDDATES FROM
;with Calendar as (
select EventID, EventTitle, EventStartDate, EventEndDate, EventEnumDays,EventStartTime,EventEndTime, EventRecurring, EventStartDate as PlannedDate
,EventType from EventCalender
where EventActive = 1 AND LanguageID =1 AND EventBlockDate = 1
union all
select EventID, EventTitle, EventStartDate, EventEndDate, EventEnumDays,EventStartTime,EventEndTime, EventRecurring, dateadd(dd, 1, PlannedDate)
,EventType from Calendar
where EventRecurring = 1
and dateadd(dd, 1, PlannedDate) <= EventEndDate
)
select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
or EventEnumDays is null
order by EventID, PlannedDate
option (maxrecursion 0)
I would appreciate a point in the right direction or if I can create a temporary table from this CTE query
Sample DDL
create table #Temp
(
EventID int,
EventTitle Varchar(50),
EventStartDate DateTime,
EventEndDate DatetIme,
EventEnumDays int,
EventStartTime Datetime,
EventEndTime DateTime,
EventRecurring Bit,
EventType int
)
;WITH Calendar
AS (SELECT /*...*/)
Insert Into #Temp
Select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
or EventEnumDays is null
Make sure that the table is deleted after use
If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
Drop Table #Temp
End
Really the format can be quite simple - sometimes there's no need to predefine a temp table - it will be created from results of the select.
Select FieldA...FieldN
into #MyTempTable
from MyTable
So unless you want different types or are very strict on definition, keep things simple. Note also that any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temp table and calls stored procedure B, then B will be able to use the temporary table that A created.
However, it's generally considered good coding practice to explicitly drop every temporary table you create anyway.
How to Use TempTable in Stored Procedure?
Here are the steps:
CREATE TEMP TABLE
-- CREATE TEMP TABLE
Create Table #MyTempTable (
EmployeeID int
);
INSERT TEMP SELECT DATA INTO TEMP TABLE
-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100
SELECT TEMP TABLE (You can now use this select query)
Select EmployeeID from #MyTempTable
FINAL STEP DROP THE TABLE
Drop Table #MyTempTable
I hope this will help. Simple and Clear :)
The SELECT ... INTO needs to be in the select from the CTE.
;WITH Calendar
AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
EventStartDate,
EventEndDate,
PlannedDate AS [EventDates],
Cast(PlannedDate AS DATETIME) AS DT,
Cast(EventStartTime AS TIME) AS ST,
Cast(EventEndTime AS TIME) AS ET,
EventTitle,
EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/
FROM Calendar
WHERE ( PlannedDate >= Getdate() )
AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
OR EventEnumDays IS NULL
ORDER BY EventID,
PlannedDate
OPTION (maxrecursion 0)
Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):
SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X
Select Eventname,
count(Eventname) as 'Counts'
INTO #TEMPTABLE
FROM tblevent
where Eventname like 'A%'
Group by Eventname
order by count(Eventname)
Here by using the into clause the table is directly created
You should also be aware that there are GLOBAL temporary tables. These can be referenced from another connection. They behave pretty much as described by early answers. To create one, simply prefix the table name with ##. That's what I was looking for; hope others that land here find that useful too.
You can also use View to create a temporary/virtual table
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;