SQL 2012 :: Checking If A Date Exists In Particular Daterange
Jan 6, 2015
I have a table called as Events and below are its columns
ID int
EventFromDate datetime
EventToDate datetime
EventDesc nvarchar
IsHoliday bit
This is a master table where the admin would enter the Events/Holidays for the entire year.
The data would be as below:
IDEventFromdateEventTodateEventDesc isHoliday
126-01-201526-01-2015RepublicdayYes
230-01-201531-01-2015TeamOutingNo
301-05-201501-05-2015Labour day Yes
Now, suppose a employee applies leave on 26/01/2015 to 26/01/2015 then it should not insert into table and return a value "Not updated"
How to handle the scenario if a employee applies leave between the range 23/01/2015 to 27/01/2015, since 26/01/2015 is a holiday in between. how the data can still be inserted excluding 26/01/2015
Can we exclude a non-working day or a sunday.
Leavedetails table to insert leaves applied by employee is as follows
LeaveDetailID int
LeaveTypeId int
FromDate datetime
EndDate datetime
Remarks nvarchar
I have a table with EmployeeID, StartDate, and EndDate with a PK of EmployeeID, StartDate. How can I check to see that there's no overlap for StartDate and EndDate for a given employee? That is, on any given day there must only be 1 row for an employee where Getdate() is Between StartDate and EndDate. For an active employee their EndDate is set to 06/06/2079.
I've tried it using Row_Number() with Over() but am returning too many rows indicating overlap when none exists.
I know there is a way to determine if a file exists using T-SQL, but I can't seem to find a way to determine if a directory exists. I need to be able to determine this so I can delete the directory if it already exists before I run other queries.
I can't seem to get this work. I'm using SQL2005 I want to check if a record exists before entering it. I just can't figure out how to check it before hand. Thanks in advance. Protected Sub BTNCreateProdIDandName_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BTNCreateProdIDandName.Click ' Define data objects Dim conn As SqlConnection Dim comm As SqlCommand
' Reads the connection string from Web.config Dim connectionString As String = ConfigurationManager.ConnectionStrings("HbAdminMaintenance").ConnectionString ' Initialize connection conn = New SqlConnection(connectionString)
' Check to see if the record exists If comm = New SqlCommand("EXISTS (SELECT (BuilderID, OptionNO FROM optionlist WHERE (BuilderID = @BuilderID) AND (OptionNO = @OptionNO)", conn)
Then 'if the record is exists display this message. LBerror.Text = "This item already exists in your Option List." Else
'If the record does not exist, add it. FYI - This part works fine by itself. comm = New SqlCommand("INSERT INTO [OptionList] ([BuilderID], [OptionNO], [OptionName]) VALUES (@BuilderID, @OptionNO, @OptionName)", conn)
I would like to be able to check if a certain entry exists in a SQL table. Ideally, the output would be a boolean so I can use it in an IF statement which would tell it what to do depending on whether or not the entry exists. Thanks for anyone that helps. :)
I've got two tables, one containing a list of company names(approx 10,000 records), the other containing a list of company employees (approx 30,000 records) joined by the CompanyID column.
I have a third table (approx 700 records) containing new employees to be added to the employee table. Each record in this table has the employees details plus the name of their company.
I want to write a query that will check each row in the third table to see if a) the employee exists in the Employees table b) the company exists in the Companies table and c) the employee is listed under the correct company
The query should also handle any combination of the above. So if the company doesn't exist but the employee does, create the company on the companies table and update the appropriate record on the employees table with the new CompanyID etc. etc.
Oh, forgot to mention. The company names in the third table won't be exactly the same as the ones in the Company table so will need to use CharIndex.
I'm trying to check which price grids are in use using the price grid_id, and seeing whether this grid_id exists in another query that checks all active contracts. If the grid_id is present (active) I want to return 'Yes', if not I want it to return 'No'.
There are 385 price grids, but my query is only returning the 315 that are active, and ignoring any that are not used. My code is below, how I can see all the records whether Yes or No:
Select distinct pg.grid_id [Price Grid], pg.grid_name [Grid Name], case when exists (Select c.grid_id from customers c inner join deltickhdr dh on dh.acct = c.custnum and dh.stage <5 where c.type = 'C' and dh.dticket is not null) then 'Yes' else 'No' end [Active]
From gridhdr pg inner join customers c on c.grid_id = pg.grid_id
I am getting an error between the IF THEN Else statement. The copy works after the THEN! I need some help!
Ernie
I have two tables with script in a view. 1. newusers 2. blacklist I want to compare that "PresentEmail, RemoteComputer,Email" thats in newuser table is not in blacklists, and if this is true, then copy from newuser (the record not on blacklist) to blacklist using a where statement for second condition.
IF (NOT EXISTS (SELECT * FROM newusers AS d WHERE ISNULL(PresentEmail, 'NULL') IS BadEmail))
THEN
Insert into blacklist (BadNewEmail, BadIpAddress, BadEmail)
I am checking to see if the source record is available in the target table using a lookup transformation and if not found i have to insert this record. I have connected the error flow of the lookup transformation to the target. I am acheiving expected results, but is this the best practise? I have not connected to the green arrow to any task.
I'm trying to put scripts to create our stored procedures under version control.
However I don't want these scripts to be run if the stored procedure already exists (we'll be using update scripts to alter existing stored procedure I think).
Anyway I tried :
Code:
SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO
/****** Object: Stored Procedure dbo.getEnglandHotelsByATOPResort Script Date: 26/10/2005 10:40:01 ******/ if NOT EXISTS (SELECT object_id('procedureName','p')) CREATE PROCEDURE [dbo].[procedureName] @location char(2) AS ...Procedure...
GO
SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO
I know that the if NOT EXISTS ... part works as doing the following returns the expected result :
Code:
IF NOT EXISTS (SELECT object_id('procedureName','p')) SELECT 'FALSE' ELSE SELECT 'TRUE'
However when trying to do this before the CREATE PROCEDURE I get :
Server: Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'PROCEDURE'. Server: Msg 137, Level 15, State 1, Line 12 Must declare the variable '@location'.
I've decided to post this as a sticky given the frequency this question is asked.
For those of you wishing to build a package that determines if a source row exists in the destination and if so update it else insert it, this link is for you.
If you want to do a similar concept to Jamie's blog post above, but with the Konesan's Checksum Transformation to quickly compare MANY fields, you can visit here: http://www.ssistalk.com/2007/03/09/ssis-using-a-checksum-to-determine-if-a-row-has-changed/
I have 1+ CSV files (using a foreach loop) which I'm doing a lot of transform work on and then inserting into a SQL database table. Each CSV file usually contains about 2 days worth of data (contains date stamps) - somewhere in the region of 60k records per day. The destination table currently contains 3 million+ rows and will get bigger. I need to make sure that before inserting into the destination table, the data doesn't already exist.
I've read the following article: http://www.sqlis.com/311.aspx While the lookup method works, it takes ages and eats up memory as it caches the 3m+ records before running for each CSV. Obviously this will only get worse as the table grows in size.
To make things a little more efficient what I'd like to do, is first derive the dates I'm dealing with in the current file - essentially storing the max(date) and min(date) in variables. Then in the lookup SQL use those vars, to reduce the amount of data that needs to be brought into the transformation to check against before inserting into the destination table. Lookup SQL eg. SELECT * FROM MyTable WHERE Date BETWEEN varMinDate AND varMaxDate.
Ideally I'd use an aggregate transformation and then use the subsequent output from that either in the lookup query or store the output in vars, but I don't think you can do that and I get the feeling I'm approaching this with the wrong mindset.
Background: After Insert Trigger runs a sproc that inserts values into another table IF items on the form were populated. THose all work great, but last scenario wont work: Creating a row insert based on Checking that all 22 other items from the prior insert (values of i.columns) were NULL:
IF EXISTS(select DISTINCT i.notes, i.M_Prior, i.M_Worksheet, ... from inserted i WHERE i.notes IS NOT NULL AND i.M_Prior = NULL AND i.M_Worksheet = NULL AND...)
For all intents and purposes, the second record has a null end date because it's valid until a new value is entered. If I were to update the value again, the 3rd record would look like this.
3 | 300 | 1/24/2004 | NULL
And, since this was updated, I'd go back and update the 2nd record so that I know the End Date (the 3rd record's start date)
2 | 200 | 1/23/2004 | 1/24/2004
Ok, with that said, my application looks at each week in a year, and looks for a valid value for the given date. I need to say "for this week, give me the value." If 2 values fall within the given week, I want to grab the highest (MAX) value.
Any ideas on how I'd structure the SQL statement for this? The where clause is where I'm having funny (hey, that's kinda funny -- where and where).
Anyway, I appreciate any help that you all can give me on this one. It's getting late and my brain is burnt out for the day!
I am facing a funny problem. I am doing a select to get records with "ExitDate" greater than "FromDate". However, when I run the query, it is also returning the "FromDate".
SET @FromDate = '3/31/2000' SELECT IndividualID, ExitDate FROM clientserviceprogram WHERE exitdate IS not null AND EXITDATE > @FromDate
I am still getting records with ExitDate = '3/31/2000'.
Although I am familiar with SQL commands I have never worked with SQL server before and find myself at a loss for which direction to take. I have a database for equipment reservations. I need to write a procedure to notify the end-user if a specific piece of equipment is already checked out during the time frame requested. I'm reading up on stored procedures and triggers and not sure which one (if either) is appropriate to use. Any suggestions? Thanks,
Just want to check if my query is the standard way to check if date ranges overlap in a price table as I need to check any that overlap as I can't have two prices on one day.
For example if in a table there was:
Product TROUSER Colour BLUE Start Date 01-NOV-13 End Date 20-NOV-13 Price £20.00 Start Date 10-NOV-13 End Date 12-NOV-13 Price £18.00 Start Date 21-NOV-13 End Date 25-NOV-13 Price £15.00
The top two overlap.I'm doing this which is giving me nothing returned which I'm hoping means I have no overlapping date ranges:
I am new to SQL developement ( am .Net developer). I need to implement a stored proc in sql 2005 on CC expiration task.
I have CC exiration date. By using expiration date (like '01/08'),
Conditions are:
1. If CC expiring within 31 days. Stored proc will write the Customer data in EmailNotification table with message type =1. (Customer will not get second notification until 14 days before expiring)
2. If CC expiring within 14 days. Stored proc will write the customer data in EmailNotification table with message type =2. (Customer will not get second notification until 11 days before expiring)
3. If CC expiring within 11 days. Stored proc will write the customer data in EmailNotification table with message type =3. (Customer will not get second notification until 2 days before expiring)
4. If CC expiring within 2 days. Stored proc will write the customer data in EmailNotification table with message type and update orderStatusID to On Hold CC Expired in order table.
My Tables are
1.
TABLE [dbo].[Order]( [OrderID] [int] IDENTITY(1,1) NOT NULL, [CustomerID] [int] NOT NULL, [CustomerCode] [nvarchar](12) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [DateCreated] [datetime] NOT NULL, [DateOrdered] [datetime] NOT NULL, [OrderTypeID] [int] NULL, [OrderStatusID] [int] NULL, [LastProcessDate] [datetime] NULL,
2. CREATE TABLE [dbo].[Payment]( [PaymentID] [int] IDENTITY(1,1) NOT NULL, [OrderID] [int] NOT NULL, [OrderPaymentType] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [PaymentType] [nvarchar](2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [CreditCardNumber] [varbinary](max) NULL, [Last4DigitsOfCreditCardNumber] [nvarchar](4) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [ExpirationDate] [varbinary](max) NULL, [CVV2] [varbinary](max) NULL, [Amount] [numeric](18, 2) NOT NULL
3. CREATE TABLE [dbo].[Customer]( [CustomerID] [int] IDENTITY(1,1) NOT NULL, [CustomerCode] AS ([dbo].[udf_FormatCode]('RS',[CustomerID])), [Email] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [FirstName] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [MiddleName] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [LastName] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [DateCreated] [datetime] NOT NULL, [DateModified] [datetime] NOT NULL, [MembershipTypeID] [int] NULL
Please atleast basic structure of stored proc code. It will greatful to me.
Is it possible to write an expression for RS2005 in the details row in a table that will separate and add the rejection and amount field values for each calendar week and lay them out to look like below:
Week
Rejections
Amount
1
14
15
2
0
0
3
0
0
4
1
6
5
0
0
6
0
0
7
0
0
8
7
8
I€™m trying to make a report that shows the number of rejections and amounts on a week to week basis. So I need RS2005 to add the rejections and amounts for each week date range and display it line-by-line automatically on a per-week basis.
Week 1 is 1/1/07-1/6/07 according to DATEPART(WEEK,Date) and so on€¦
I need to be able to see if the incoming csv file had a head row different than the previous files header row. That will tell me that I have new columns.
I am setting up security for access of database tables for members in a specific Windows User Group.I want to check in a SQL script if this Windows User group is added and if so, add database users and grant SELECT on specific tables.
I have tried this:
SELECT * FROM master.sys.syslogins WHERE name like '%FoeUsers' AND isntgroup = '1'
but that selects a SQL user or group and not a Windows Group.Is there a way to check if a Windows NT (active Directory) user group exists?
I have a situation where our stored procedure inserts records from table_1 to table_2 when they don't already exist (uses the EXIST statement) on that table. If table_1 contains multiple records that are the same, it appears after the 1st record has been inserted, it does not recognize it as being there when it checks the existence when attempting to insert record 2.
Here's an example of the script:
insert into table_2 (col1,col2,col3) select col1,col2,col3 from table_1 t1 where not exists (select '1' from table_2 t2 where t1.col1 = t2.col1 and t1.col2 = t2.col2 and t1.col3 = t2.col3)
Data from Table_1 -- Assume that table_2 does not contain these records
col1 col2 col3 AA 11 A1 AA 11 A1 BB 22 B2
All 3 records would be inserted to table_2 in this example.
So I declared this table data type , cool.. It works
CREATE TYPE BP_Data_XXX as table ( XXX_VALUE_NUMERIC numeric(19,2), bp_type VARCHAR(4), Dt datetime, ID int IDENTITY(1,1), MBP numeric(19,2), CONCEPT_ID VARCHAR(10) )
Now my question is later how do we check whether this type exists. The following does not work.
if( object_id('BP_Data_XXX') IS NOT NULL ) print 'IT is there '
I have 2 test tables one for stock and one for prices.
I need to select all the rows from Stock but also the price on the stock but the price table doesn't always have the date, so I can not do stock date = price date.
What it needs to do is if the Stoc Date isn't in the price table use the price before... this would also have to be able to run on my rows...
-- Create Test Table (not sure if dates USA or UK format on your machine...
This is my query, from my nonono table I need to return the most recent date from attempted (column name) Â How could I modify this to do such
Select * FROM [nonono] td WHERE (NOT EXISTS (SELECT [First], [second] FROM [yesyesyes] AS d WHERE ([First] = td.[First]) AND ([second] = td.[second]) AND ([Worksite] = td.[Worksite])))
So, I've got this query running and it works great providing there is a record in both DataBases. Now, I need to get all of those that have a record in DBServer1 but not in TranscendDB. I assume i'd use an If not exists, but can't figure out the syntax when using the Linked Object...
select Portfolio from [TranscendDB].[dbo].[CMContactEvents] as CM inner join ( select N.SSN, A.ACCOUNTNUMBER from [DBServer1].[DB1].[dbo].[Account] AS A,
Itemlookup tableField names : index_id (primary key), itemno, description.It has a child table, which is ItemPriceHistory tableThe relationship to the child table is one (parent table)-to-many(child table). - It is possible to have no child record for some rowsin the parent table.ItemPriceHistory tableField names: index_id (primary key), itemlookupID (foreign key of theItemlookup table), date begin, priceIt is a child table of the itemlookup table.How can I get all records for both tables with the latest begin date ifexists?I also need to show the records in the parent table if there is norelated record in the child table.Please help
I am getting error [[Msg 116, Level 16, State 1, Line 7 .Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.]] for the below script.