Checking To See If A Record Exists Before Inserting

Feb 14, 2007

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)

comm.Parameters.Add("@BuilderID", System.Data.SqlDbType.Int)
comm.Parameters("@BuilderID").Value = LBBuilderID.Text

comm.Parameters.Add("@OptionNO", System.Data.SqlDbType.NVarChar)
comm.Parameters("@OptionNO").Value = DDLProdID.SelectedItem.Value

comm.Parameters.Add("@OptionName", System.Data.SqlDbType.NVarChar)
comm.Parameters("@OptionName").Value = DDLProdname.SelectedItem.Value

LBerror.Text = DDLProdname.SelectedItem.Value & " was added to your Option List."

Try
'open connection
conn.Open()
'execute
comm.ExecuteNonQuery()
Catch
'Display error message
LBerror.Text = "There was an error adding this Option. Please try again."
Finally
'close connection
conn.Close()
End Try

End If

End Sub  

 

View 8 Replies


ADVERTISEMENT

Checking To See If A Records Exists Before Inserting - 3 Million + Rows

Aug 21, 2007

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.

Any thoughts would be great!

View 6 Replies View Related

Checking A Table To See If A Record Already Exists

Sep 19, 2007

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.

Anybody got any ideas?

View 4 Replies View Related

Checking Whether Record ID Exists In Another Query

Jan 10, 2014

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

Order by pg.grid_id

View 4 Replies View Related

Checking To See If A Record Exists Else Insert

Apr 30, 2008

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.

View 6 Replies View Related

Checking To See If A Record Exists And If So Update Else Insert

Feb 9, 2007

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.

http://blogs.conchango.com/jamiethomson/archive/2006/09/12/SSIS_3A00_-Checking-if-a-row-exists-and-if-it-does_2C00_-has-it-changed.aspx

Thanks Jamie!

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/

Phil

View 60 Replies View Related

Checking If Directory Exists In T-SQL

Jun 18, 2008

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.

View 17 Replies View Related

Checking If File Exists Or Not

Mar 18, 2008

Greetings all.

How can I check for file exitence in a specified folder using TSQL?

I can think of a couple of ways to do this so any feedback would be appreciated.

Load the contents of a folder in to a temporay table and check the table for file name. I can do this with something like:

insert into myFiles
exec master..xp_cmdshell 'dir /B /OND filePath*.txt'


Or maybe use OLE Automation Sproc? But I am not sure which method I should use.

Please advise.

View 4 Replies View Related

Checking If An Entry Exists In A Database

Apr 22, 2006

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. :)

View 6 Replies View Related

Checking If Information Exists Before Copy

Apr 1, 2007

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)

Select NewEmail, RemoteComputerName, PresentEmail

From newusers

Where Account_Active = 'Spammer'

Else
GO

View 7 Replies View Related

Checking If A Stored Procedure Exists Before Creating It

Oct 27, 2005

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'.

Any ideas how to do this?

-D

View 3 Replies View Related

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

View 0 Replies View Related

Checking Specific Columns Were NULL On Previous Insert (Using If EXISTS)

Aug 3, 2007

Thanks for your time:

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...)


BEGIN

Insert into dbo.Items2Fix ...

From inserted i

END

View 1 Replies View Related

Restrict Inserting Record If Record Already Exist In Table

Apr 17, 2014

Is that possible to restrict inserting the record if record already exist in the table.

Scenario: query should be

We are inserting a bulk information of data, it should not insert the row if it already exist in the table. excluding that it should insert the other rows.

View 2 Replies View Related

Checking For A New Record

Jan 5, 2005

Good morning everyone I am writing a windows forms application that will work similar to the windows messenger popup. I need this application to display a message to the user whenever a record is added to table in my DB. Any help would be appreciated in explaining how I can check the DB for new records.

View 3 Replies View Related

Possible To Disable Welll-formedness Checking When Inserting XML Data.

Mar 20, 2006

Hi All,Can anyone help with the following problem? I have a database whichcontains a table with a 'text' field, and the text field contains anxml document - typically 50-100K. Now I'd like to make use of SQLServer 2005s XMLData type. To do this I have created a new field ofthe 'xmldata' datatype, and run an SQL statement to update the contentsfrom one field to another - hoping to end up with a complete table ofxml (based on the old text field).The problem I have is after a minute or so, it must come across anbadly-formed xml fragment because I get the following message:Msg 9436, Level 16, State 1, Line 1XML parsing: line 1, character 67640, end tag does not match start tagCan I turn off the checking during the update, or is it not possible toadd badly formed data to the xmldata field. Any help appreciated asthe table runs into tens of thousands of rows, so I can't really checkthe contents of each!Many thanks,Duncan.

View 1 Replies View Related

Checking If No Record Is Returned

Aug 1, 2004

hi,

I basically want the .net version of rs.eof
does anyone know what the code would be using the execute scalar method?

Thanks

View 2 Replies View Related

Need Help Checking To See If More Than 1 Record Updated.

May 21, 2006

I am trying to write a trigger that, on an update, will check to see if more than one record is being updated. If more than one record is being updated, rollback the transaction and print a message. If not, then commit the transaction and print an OK message.

My problem is I am having troubles writing this trigger. I will post my SQL trigger code so far.

I am new with Triggers, so any help or advice is appreciated.


Code:

CREATE TRIGGER trgPaperCheck
ON BOOK
AFTER UPDATE
AS
IF UPDATE(Paperback)
BEGIN
DECLARE @count AS INT
SELECT @count = COUNT(Paperback)
FROM Book
IF @count > 1
BEGIN
PRINT('Only one Book record can be updated at a time!')
ROLLBACK TRANSACTION
END
ELSE IF @count =1
BEGIN
PRINT('Paperback Updated')
COMMIT TRANSACTION
END
END

View 2 Replies View Related

Problem In Checking Null Record

Apr 30, 2007

Hello, I am using sql server 2000 as my backend.If there is any null record in my table , I am getting following error:*********** Conversion from type 'DBNull' to type 'String' is not valid. ************** to overcome this error I want to check if its null then don't do anything else do something.I have tried like this:If rs.fields("ph").value="NULL"  thenelse.................end if But this does not  solve my problem.Please help  me i anyone can.Thanks. 

View 1 Replies View Related

Inserting Unique Values Into A Different Tables If They Don't Exists Already.

Jul 30, 2007



Hi

I am trying to insert values into a table that doesn't exist there yet from another table, my problem is that because it is joined to the other table it keeps on selecting more values that i don't want.




Code Snippet

SET NOCOUNT ON

INSERT INTO _MemberProfileLookupValues (MemberID, OptionID, ValueID)
SELECT M.MemberID, '6', CASE M.MaritalStatusID WHEN 1 THEN '7'







WHEN 2 THEN '8'

WHEN 3 THEN '9'

WHEN 4 THEN '10'

END

FROM Members M



INNER JOIN _MemberProfileLookupValues ML

ON M.MemberID = ML.MemberID

WHERE M.Active = 1

AND OptionID <> 6






When i execute that code it returns all the values, let say OptionID = 3 is smoking already exists in the MemberProfileLookupValues table then it is going to select that persons memberID

I want to insert only members values that aren't already in the _MemberProfileLookupValues from the Members table (I think that it is because of the join statement that is in my code, but i don't know how i am going to select members that aren't in the table, because i have a few other queries that are very similar that are inserting different values, so ultimately

ONLY INSERT THE MemberID the values 6 and the statusID of X if it is not in the table already.

Any ideas / help will be greatly appreciated. Please help.

Kind Regards
Carel Greaves

View 3 Replies View Related

Checking Record Consistency Between Tables Using SSIS

Feb 1, 2008

Hello,
I have an SSIS package that affects data in fourteen tables. This SSIS packge is supposed to insert, update, delete and apply various business rules to the data in the new database tabes in the same way that it occurs in the DTS package that affects the old tables in the former database.

After both the DTS packge and SSIS packages are run, the data in the fourteen tables from both databases need to mirror each other. I figure this is the best way that I can know that the new SSIS package is working correctly.

Is there something I can do in an SSIS package that can compare all of the tables between the two databases, record for record then (maybe as error output) produce output in the case where a mistmatch was detected between two given tables? Would a lookup transformation be helpful for this kind or thing, or should I think about doing it some other way?

The old database is on SQL Server 2000, and the new one on SQL Server 2005 64 bit. I've run into problems creating a linked server between the two to where I could just run queries to do this kind of check.

Any ideas?

Thank you for your help!

cdun2

View 3 Replies View Related

How To Know If A Record Exists

May 21, 2006

Hello,I have a TextBox and an Insert Button, it works like this: protected void Button1_Click(object sender, EventArgs e) { String strConn=SqlDataSource1.ConnectionString; SqlCommand cmd = new SqlCommand("INSERT INTO My_Table_1 (Column_1) VALUES ("+TextBox1.Text+")", new SqlConnection(strConn)); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } But, what code i must write for checking, if the value i am trying to insert already exists ??I mean something like this:if (TextBox1.Text does not Exists on any Record in My_Table_1) then        Insert itelse        Show Message : "Already exists a record with this value"Thank you SO MUCH, guys,Carlos.

View 7 Replies View Related

Check If Record Exists

Feb 1, 2007

 Hello,I created the following SQL script to check if a record exists:IF (EXISTS (SELECT LevelName FROM dbo.by27_Levels WHERE LOWER(@LevelName) = LOWER(LevelName)))  Return (1)ELSE  Return (0)And I also found in a web page another solution:IF EXISTS(SELECT 1 FROM TABLENAME WHERE LevelName=@LevelName)  SELECT 1ELSE  SELECT 0- Which approach should I use?- Why "SELECT 1 FROM"?- And when should I use SELECT or RETURN?All I need is to know if the record exists ... nothing else.I will use this procedure on an ASP.NET 2.0 / C# web site.I am not sure if this important but anyway ...Thank You,Miguel

View 6 Replies View Related

Check If Record Exists

Dec 24, 2007

Hi,
 I was wondering if someone can help.
 In vb.net what is the best way to check if a record exists if you are using an sql data reader?
For my application I need to display a button control (make it visible on the page) if a record is available after executing my sql select statement.
cheers
Mark :)

View 3 Replies View Related

Insert Record If None Exists

Oct 6, 2003

Hello folks,

I am new to msSQL and ASP, I need some help writing an SQL statement that will first check to see if a combination or record exists, if none found thant it will add it. I am working a section of a site that adds favorites to the database. Each user can have more that one favorite hence it has to check for that unique combination of the fields, UserID and FavID

My Code:
Dim objConnection, objRecordset, strSQL
Dim strFavID, strUserID
strFavID = request.Form("favid")
strUserID = request.Form("userid")

Set objConnection = Server.CreateObject("ADODB.Connection")
Set objRecordset = Server.CreateObject("ADODB.Recordset")
objConnection.Open Application("ConnectionString")

strSQL = "INSERT INTO FAV (UserID,FavID) (SELECT DISTINCT " & strUserID & " AS UserID " & _
strFavID & " AS FavID" & " FROM FAV)" & _
" WHERE " & strUserID & " & " & strFavID & " NOT IN (SELECT UserID, FavID FROM FAV)"
response.Write(strSQL)
'response.End()

If strFavID <> "" Then
On Error Resume Next
objConnection.Execute(strSQL)

objConnection.Close
Set objConnection = Nothing
End If


This code is giving me a syntax error, how do I write the correct statement. I am using MS Access 2k

Thanks for your help

View 9 Replies View Related

Don't Insert If Record Exists

Jun 21, 2004

/*if key values exist don't insert new record*/
SELECT

/*if exists don't insert*/
CASE
WHEN ISNULL(gradeId, -1) = -1 THEN
INSERT INTO tblScores
(gtStudentId, assignmentId, score)
VALUES (@nStudent, @nAssignment, 0)
END

FROM tblScores
WHERE gtStudentId = @nStudent AND assignmentId = @nAssignment


tblScores has two fields comprising its primary key (gtStudentId, assignmentId) and the gradeId field is a required filed in this table.

I'm getting syntax errors when I click check syntax (near keywords insert from and end).

one other note: this CASE END is nested inside a BEGIN END loop, is this the problem? Is the 'End" of the 'Case' closing the 'End' of the 'Begin'?

thanks

View 6 Replies View Related

Record Exists Insert Or Update

Oct 25, 2007



I had implemented as in the link to insert or update
http://blogs.conchango.com/jamiethomson/archive/2006/09/12/SSIS_3A00_-Checking-if-a-row-exists-and-if-it-does_2C00_-has-it-changed.aspx


What i want to know is... how can i assume there are no duplicate records.
I used Distinct keyword and queried it showed me all are distint but some where i find some duplicates just don't know why i am having when i look at the data both are exactly same...

Please let me know how can i fix it.
Urgent..

Thanks

View 5 Replies View Related

Finding If A Record Exists In Either Of Two Tables

Mar 17, 2008



Hello,

I have two tables with the same field layout, and they both have the same field as the Primary Key. They just contain different data. I would like to know if a record exists in one, or both, tables.

The tables are InvTemp1 and SalesTemp1. The key for both is stock_number.

Here is the command so far:


SELECT COUNT(*)

FROM InvTemp1 INNER JOIN SalesTemp1 ON InvTemp1.Stock_number = SalesTemp1.Stock_number

WHERE (InvTemp1.Stock_number = '101053')

Thank you for any ideas,
Tom

View 3 Replies View Related

Update Table If Record Exists Else Insert ?

Dec 17, 2007

Is there a way to structure a query to update an existing table record if it already exists, otherwise insert a new record into that table?

View 2 Replies View Related

Need To Set A Field In A Select Statement Equal To Yes Or No If Record Exists In Separate Table

Jan 8, 2008

Hey gang,
I've got a query and I'm really not sure how to get what I need.  I've got a unix datasource that I've setup a linked server for on my SQL database so I'm using Select * From OpenQuery(DataSource, 'Query')
I am able to select all of the records from the first two tables that I need.  The problem I'm having is the last step.  I need a field in the select statement that is going to be a simple yes or no based off of if a customer number is present in a different table.  The table that I need to look into can have up to 99 instances of the customer number.  It's a "Note" table that stores a string, the customer number and the sequence number of the note.  Obviously I don't want to do a straight join and query because I don't want to get 99 duplicates records in the query I'm already pulling.
Here's my current Query this works fine:
Select *From OpenQuery(UnixData, 'Select CPAREC.CustomerNo, CPBASC_All.CustorCompName, CPAREC.DateAdded, CPAREC.Terms, CPAREC.CreditLimit, CPAREC.PowerNum
From CPAREC Inner Join CPBASC_All on CPAREC.CustomerNo = CPBASC_All.CustomerNo
Where DateAdded >= #12/01/07# and DateAdded <= #12/31/07#')
What I need to add is one more column to the results of this query that will let me know if the Customer number is found in a "Notes" table.  This table has 3 fields CustomerNo, SequenceNo, Note.
I don't want to join and select on customer number as the customer number maybe repeated as much as 99 times in the Notes table.  I just need to know if a single instance of the customer number was found in that table so I can set a column in my select statement as NotesExist (Yes or No)
Any advice would be greatly appreciated.

View 2 Replies View Related

SQL Server 2012 :: How To Return User-defined Row When A Record Doesn't Exists

Dec 29, 2014

What I want to do is return a row of data when my query doesn't return a record. I have two tables:

CREATE TABLE dbo.abc(
SeqNo smallint NULL,
Payment decimal(10, 2) NULL
) ON PRIMARY

[Code] ....

So when I run the following query:

SELECT 'abc' + '-' + CAST(SeqNo AS VARCHAR) + '-' + CAST(Payment AS VARCHAR) FROM abc WHERE SeqNo = 1
UNION
SELECT 'def' + '-' + CAST(SeqNo AS VARCHAR) + '-' + CAST(Payment AS VARCHAR) FROM def WHERE SeqNo = 1
abc-1-200.00
abc-1-500.00

As you can see since 1 doesn't exists in table 'def' nothing is returned as expected. However, if a row isn't returned I want to be able to enter my own row such as

abc-1-200.00
abc-1-500.00
def-0-0.00

View 4 Replies View Related

Inserting A New Record

Jan 29, 2005

I want to insert a new record into my db in asp.net. Im programming in vb and using an sql server database. i know this is a begginers question but that's exactly what i am. Thanks in advance

View 1 Replies View Related

Inserting A New Record Into A Database.

Oct 30, 2006

hey everyone,I have created two tables in an sql server database. I have a check box in the table 1, and when it is checked, I want to insert that particular record into table 2. (By the way I am using a datagrid) The problem is when I click the check on the particular record I want inserted, and click update, the system copies the record twice instead of once. When I look into table 2, I end up having two of the same records. Can anyone help me.

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved