I need to insert several rows into a SQL Server database based on Start Date and End Date textboxes.
E.G. tbStartDate.Text = "25/12/2012" and tbEndDate.Text = "29/12/2012" therefore I need to insert individual rows for the following dates:
25/12/2012
26/12/2012
27/12/2012
28/12/2012
29/12/2012
Please can you help me with the necessary T-SQL to achieve this?
As always there are a few ways. Here are some of them:
You can write code in your app that loops through the days and inserts a single record per day. (generally the worst design)
You can call some SQL script to do it all in the database.
You can wrap up your SQL script in a stored procedure and pass in the start and end date and get the stored procedure to do it for you.
You can cross join to a pre existing tally table and use it to generate your records.
If you can provide
-the version of SQL Server that you're using
-what the table looks like
-whether you're using C# or VB
then we can help further as it can be difficult to pass dates into databases. It can be particularly difficult if you do not validate them.
Anyway here is option 3 for you.
CREATE PROC dbo.t_test
#StartDate DATETIME,
#EndDate DATETIME
AS
WHILE #StartDate <= #EndDate
BEGIN
INSERT INTO YourTable(YourDateField) VALUES (#StartDate)
SET #StartDate = DATEADD(d,1,#StartDate)
END
Then you need to call this stored procedure (called dbo.t_test) from ASP.Net and pass in your two date parametes as dates.
Declare #Startdate datetime
Select #Startdate='20121025'
While #Startdate<='20121029'
begin
if not exists(select * from dummy where DATE=#Startdate)
insert into dummy (date) values (#Startdate)
set #Startdate=#Startdate + 1
end;
Related
I'm creating a temporary datetime table with 15 minutes increment with the following code in SSRS:
--declare #Id varchar(20), #startdate datetime,#enddate datetime
--set #ID = 'J00000041'
--set #startdate = '20210601'
--set #enddate = '20210630';
create table #tempcalendar ([dispdate] [datetime], intervaldate [datetime],intervaltime [datetime])
while #StartDate <= #EndDate+1
begin
insert into #tempcalendar values(#StartDate, convert(varchar,#StartDate,110), convert(varchar(5),#StartDate,108) )
set (#StartDate) = dateadd(minute,15,#StartDate)
end
One of the parameters doesn't appear in the Define Query Parameters dialogue box when I try to run it in SSRS and I get the message 'Must declare the scalar variable' error. I've pinpointed the issue where in the code:
set #StartDate = dateadd(minute,15,#StartDate)
I was able to perform this code in SSMS (which is where I created it initially) however I can't seem to find any information where I might have gone awry in this in SSRS. I've also tried putting parenthesis in #StartDate to show set (#StartDate) = dateadd(minute,15,#StartDate), but that didn't work.
Thank you for your help
I have seen this before when setting a variable in t-sql that is passed in from SSRS.
I think the problem is the SSRS mis-interprets the query.
I worked around the problem by setting another variable to the passed in value.
e.g.
DECLARE #StartDate2 datetime
SET #StartDate2 = #StartDate
.. then use #StartDate2 in the remainder of the query.
Also check that every instance of your variable/parameter names are exactly the same, they are case sensitive. If you pass in #X but reference #x SSRS will think this is a new parameter.
SSRS expects to be able to return metadata on the SQL in the dataset. This is how it determines the column names and data types for you. This is also why you can only have one select statement in the dataset.
You can wrap your query in a stored procedure. SSRS can call the procedure and pass in the parameters. The procedure should have one select statement that returns the results for the report to handle. The procedure can be as complex as you need it to be and abstracts that code from being embedded in the report.
This may seem like a very basic question.
I have a very large SQL statement with lots of sub queries that contain date limits in multiple where clauses
We run this query on an ad-hoc basis where i have to change the date range in the query in about 20 places. The date range is the same in all the places. So for example 1-Jan-2016 to 7-Jan-2016 as an example
In Teradata is it possible to declare the date range at the start of the query for example like a variable and then reference this variable in the code so i only need to change it once?
I have seen the answer for declaration of variable in teradata but would like to see a simple example demonstrating the concept for a date range in a stored procedure
Thank you for your time
Instead of making it a variable, it should probably be a parameter. Your stored proc would be something like this:
REPLACE PROCEDURE MyStoredProcedure
(
IN StartDate DATE
,IN EndDate DATE
)
BEGIN
DECLARE SomeOtherDate DATE; --if you need an actual date variable
--Your logic goes here
END;
Then you would set the parameters when you call the stored proc
CALL MyStoredProcedure('2015-01-01','2015-12-31');
I am using OrmLite Oracle in C#. I want to insert current sysdate instead of DateTime.Now in column having date data type, i.e. taking the date at the database end and not the calling code. How can I do this?
I am running a website using SQL Server 2008 and ASP.NET 4.0. I am trying to trace an issue down that my stored procedure is creating duplicate entries for the same date. Originally I thought this may be a couple post issue but the duplicates are recording the same date down to the milliseconds. One of the duplicates is at :'2013-04-26 15:48:28.323' All of the data is exactly the same except for the id.
#check_date is an input into the stored procedure which gives us the particular date we are looking at (entries are maid daily)
#formHeaderId is grabbed earlier in the stored procedure, getting the header ID as this is a detail table with a 1 to many relationship with the header.
The #getdate() entry is where I found the duplicate entries, there are entries with the exact getdate() values for different rows.
This doesn't occur with each entry either, it is randomly occurring in the application.
select #formHeaderId=stage2_checklist_header_id
from stage2_checklist_header
where environmental_forms_id=#envFormId
and checklist_monthyear=#inspected_month
order by start_date desc
if #formHeaderId = 0 begin
insert into stage2_checklist_header(
environmental_forms_id
,start_date
,checklist_monthyear
,st2h_load_date )
values( #envFormId
,#check_date
,#inspected_month
,getdate())
set #formHeaderId = scope_identity()
print 'inserted new header record ' + cast(#formHeaderId as varchar(50))
end
IF (NOT EXISTS(
SELECT *
FROM stage2_checklist_detail
WHERE stage2_checklist_header_id = #formHeaderId
AND check_date = #check_date
))
INSERT INTO stage2_checklist_detail
(stage2_checklist_header_id, check_date, st2_chk_det_load_date,
inspected_by)
VALUES
(#formHeaderId, #check_date, GETDATE(), #inspected_by)
SET #form_detail_id = SCOPE_IDENTITY()
PRINT 'inserted detail record ' + CAST(#form_detail_id AS VARCHAR(50))
Here is a similar case where the developer was able to track the duplicate entries to simultaneous calls from different spids (which sidestepped the EXISTS check). After experimenting with isolation levels and transactions - and trying to avoid deadlocks - it sounds like the solution in that case was to use sp_getapplock and sp_releaseapplock.
In the NOT EXISTS check, you are looking for records that have both the same ID and the same date. So, if the combination of ID AND date does not exist in the table, the row will be inserted.
In your description of the problem you state "All of the data is exactly the same except for the id". The ID being different will always cause an INSERT based on the logic you are using to check for existence.
I'm trying to add an auto-calculated field in SQL Server 2012 Express, that stores the % of project completion, by calculating the date difference by using:
ALTER TABLE dbo.projects
ADD PercentageCompleted AS (select COUNT(*) FROM projects WHERE project_finish > project_start) * 100 / COUNT(*)
But I am getting this error:
Msg 1046, Level 15, State 1, Line 2
Subqueries are not allowed in this context. Only scalar expressions are allowed.
What am I doing wrong?
Even if it would be possible (it isn't), it is anyway not something you would want to have as a caculated column:
it will be the same value in each row
the entire table would need to be updated after every insert/update
You should consider doing this in a stored procedure or a user defined function instead.Or even better in the business logic of your application,
I don't think you can do that. You could write a trigger to figure it out or do it as part of an update statement.
Are you storing "percentageCompleted" as a duplicated column value in the same table as your project data?
If this is the case, I would not recommend this, because it would duplicate the data.
If you don't care about duplicate data, try something separating the steps out like this:
ALTER TABLE dbo.projects
ADD PercentageCompleted decimal(2,2) --You could also store it as a varchar or char
declare #percentageVariable decimal(2,2)
select #percentageVariable = (select count(*) from projects where Project_finish > project_start) / (select count(*) from projects) -- need to get ratio by completed/total
update projects
set PercentageCompleted = #percentageVariable
this will give you a decimal value in that table, then you can format it on select if you desire to % + PercentageCompleted * 100