Basically, I need to insert the wbs2 and wbs3 where it does not exist in each wbs1.
What I have now will find the values that need to be inserted for a particular project but I don't know how to go through each project and perform the insert:
Select * from PR_template Where Not Exists (Select Wbs1, Wbs2, Wbs3 from PR where PR.WBS2 = PR_Template.WBS2 And PR.WBS3 = PR_Template.Wbs3 and pr.wbs1 = '123-456') Order by wbs2, wbs3 asc
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
/*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'?
it's me again :) I've got a - what I think - simple question. There is table A with Col1,Col2,Col3 and Table B with Col1,Col2,Col3
I want all rows from B in A. If a row already exist in A, then update all columns, else just insert the row. Can someone please help me with a small syntax. Thank you!
I am using the following code to insert records into a destination tablethat has a three column primary key i.e. (PupilID, TermID &SubjectGroup). The source table records all the pupils in a school with(amongst other things) a column (about 50) for each subject the pupilmight potentially sit. In these columns are recorded the study groupthat they belong to for those subjects. The destination table holds arecord per pupil per subject per term, against which the teacher willultimately record the pupils performance.The code as shown runs perfectly until the operator tries to insert aselection of records that include some that already exist. What I wouldlike it to do is, record those, which do not exist and discard theremainder. However, whenever a single duplicate occurs SQL rejects thewhole batch. I know that my solution will probably involve using the‘NOT EXISTS’ expression, but try as I might I cannot get it to work. Tofurther complicate things, the code is being run from within VBA usingthe RunSQL command.The variables ‘strFieldName’, ‘strGroup’ & ‘strTerm are declared at thestart of the procedure and originate from options selected on an Accessform.INSERT INTO dbo.yInterimReportData (PupilID, LastName, FirstName,TermID, SubjectGroup) SELECT PupilID, LastName, FirstName," & "'" &strTerm & "'" & "," & "'" & strGroup & "'" & "FROM dbo.Pupils WHERE (" &strFieldName & " = " & "'" & strGroup & "')Any Ideas?RegardsColin*** Sent via Developersdex http://www.developersdex.com ***
Hi I am trying to populate a table with 2 FKs as its PK (SiteID and ProductDescID). First 1) I add in all the products whose Manfacturer and Category are supposed to appear on the site and then 2) I add in all the extra products that are needed regardless of their manufacturer or category. The problem I am having is if the product has already been added to the ProductCatTable due to its Manufacturer or Cateogry but is also in the SatForceProduct table. The can’t insert duplicate PK error is thrown. I don’t know how to do this IF NOT EXISTS statement (or what ever else may be needed) so that I can check whether a line from the Forced table needs to be added. I am not passing in any parameters and I am expecting more than 1 line to be inserted in each of the statements. Please help -- 1) Populate INSERT INTO dbo.ProductCatTable (SiteID, ProductDescID) SELECT dbo.SatSite.SiteID, dbo.ProductDesc.ProductDescID FROM dbo.SatManu INNER JOIN dbo.ProductDesc ON dbo.SatManu.Manu = dbo.ProductDesc.Manu INNER JOIN dbo.SatCats ON dbo.ProductDesc.Cat = dbo.SatCats.Cat INNER JOIN dbo.SatSite ON dbo.SatManu.SatID = dbo.SatSite.SiteID AND dbo.SatCats.SatID = dbo.SatSite.SiteID 2) Add Force Ins IF NOT EXISTS(SELECT SiteID, ProductDescID FROM ProductCatTable WHERE ????????) BEGIN INSERT INTO dbo. ProductCatTable (SiteID, ProductDescID) SELECT SiteID, ProductDescID FROM dbo.SatForceProduct END Thanks in advance J
I have a 'Products' table (with: 'uid' and 'CatName' columns) and 'ProductCategory' table (with: 'uid', 'ProductID', 'CategoryID' columns).
I got stored procedure below to update or insert new row to 'ProductCategory' table whenever 'Products' table has been updated or new products has been added to it.
Update part works just fine but when new row has been added to 'Products' this storedProc dosn't insert it into 'ProductCategory' table, it does that only when 'ProductCategory' table is empty, I'm afraid it's because first column 'uid' in 'ProductCategory' table is an Identity column... I’m not sure how should I go about that problem. This is my stored procedure:
DECLARE @CatNo INT, @CatName varchar(10) SET @CatNo = 2 SET @CatName = 'bracket'
IF exists (SELECT ProductID from ProductCategory, Products where ProductCategory.ProductID = Products.uid and Products.CatName = @CatName ) BEGIN UPDATE ProductCategory SET CategoryID = @CatNo FROM Products WHERE Products.CatName = @CatName and ProductCategory.ProductID = Products.uid END ELSE BEGIN INSERT INTO ProductCategory ( ProductID, CategoryID) SELECT uid, @CatNo FROM Products WHERE Products.CatName = @CatName END
SET @CatNo = 3 SET @CatName = 'cable'
IF exists (SELECT ProductID from ProductCategory, Products where ProductCategory.ProductID = Products.uid and Products.CatName = @CatName ) BEGIN UPDATE ProductCategory SET CategoryID = @CatNo FROM Products WHERE Products.CatName = @CatName and ProductCategory.ProductID = Products.uid END ELSE BEGIN INSERT INTO ProductCategory ( ProductID, CategoryID) SELECT uid, @CatNo FROM Products WHERE Products.CatName = @CatName END (... Goes for another 37 categories)
I'm using MSSQL and PHP. I've got the following sql statement:
$msquery = IF NOT EXISTS (SELECT SerienNr FROM tbl_Auftrag a WHERE a.SerienNr='PC8') INSERT INTO tbl_Auftrag (BMS_AuftragsNr, SerienNr, AuftraggNr, Zieltermin, Kd_Name) VALUES ('455476567','PC8','1','2006-3-2','Fritz')
The Statement itself works fine, but i've got a problem getting a return value whether the insert has succeed, or not. :confused: mssql_query() always returns true if there occured no error in the statement. But i need to know if the insert procedded or not. I tried:
In MS Access I can do in one SQL statement a update if exists else ainsert.Assuming my source staging table is called - SOURCE and my targettable is called - DEST and both of them have the same structure asfollowsKeycolumns==========MaterialCustomerYearNonKeyColumns=============SalesIn Access I can do a update if the record exists else do a insert inone update SQL statement as follows:UPDATE DEST SET DEST.SALES = SOURCE.SALESfrom DEST RIGHT OUTER JOIN SOURCEON (DEST.MATERIAL = SOURCE.MATERIAL ANDDEST.CUSTOMER = SOURCE.CUSTOMER ANDDEST.YEAR = SOURCE.YEAR)This query will add a record in SOURCE into DEST if that record doesnot exist in DEST else it does a update. This query however does notwork on SQL 2000Am I missing something please share your views how I can do this inSQL 2000.ThanksKaren
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...
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'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/
Here is the steps I should take... 1- Check for the log table and find run status ( there is a date field which tells the day run) 2- Lets say last day was 2008-05-15, So I have to check A1.DDDDMMYYY file exists in the folder for each day like A1.20080516,A1.20080517 and A1.20060518 ( until today) 3- if A1.20080516 text file exist then I have to move it to the table and same thing for other dates like if A1.20080517 exists I have to load it to table and so on
it looks like for each loop, first I have to get the last date and then I have to check the file exists for each date and if the date file exists then I have to load it into table...
Please tell me How can I do it. it looks complex looping...
I have an address table, and a log table will only record changes in it. So we wrote a after udpate trigger for it. In our case the trigger only need to record historical changes into the log table. so it only needs to be an after update trigger.The trigger works fine until a day we found out there are same addresses exist in the log table for the same student. so below is what I modified the trigger to. I tested, it seems working OK. Also would like to know do I need to use if not exists statement, or just use in the where not exists like what I did in the following code:
ALTER TRIGGER [dbo].[trg_stuPropertyAddressChangeLog] ON [dbo].[stuPropertyAddress] FOR UPDATE AS DECLARE @rc AS INT ;
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...)
I need to find out if a Transaction ID exists in Table A that does not exist in Table B. Â If that is the case, then I need to insert into Table B all of the Transaction IDs and Descriptions that are not already in. Seems to me this would involve If Not Exists and then an insert into Table B. Â This would work easily if there were only one row. Â What is the best way to handle it if there are a bunch of rows? Â Should there be some type of looping?
I have to update a field within a table of 60 records or so. Each record has a different field value. it's type varchar. i was given an excel file with the field values and was thinking of a bulk update like bulk insert, but i don't recall that it's possible that way.
Is the only way to create a table, bulk insert, then merge the two tables together with UPDATE?
Just wanted to see if there was an easier way to do it, otherwise i'll take the latter route. Thanks!
I am getting info from one table, CalibrationReview, that is not inanother table, tblEquipments. SELECT EquipmentNumber, Model, SerialNumber, Make, CalLabName, CalDateFROM CalibrationReviewWHERE NOT EXISTS (SELECT AssignedID FROM tblEquipments WHERE AssignedID = CalibrationReview.EquipmentNumber) Now, I need to take these rows and INSERT them into tblEquipments,but with some conditions. tblEquipments has some contraints, so, the following needs to be done: Using dbo.CalibrationReview.EquipmentNumber, get CalibrationMaster.TestTechnology where dbo.CalibrationReview.EquipmentNumber = dbo.CalibrationMaster.EquipmentID Then take CalibrationMaster.TestTechnology and read tblTestTechnology.testTechnology and get tblTestTechnology.id So, tblEquipments.testTechnology = tblTestTechnology.id OR 1 if not foundWHERE dbo.CalibrationReview.EquipmentNumber = dbo.CalibrationMaster.EquipmentID and CalibrationMaster.TestTechnology = tblTestTechnology.testTechnology And similar for CalibrationReview.CalLabName. tblEquipments.calLab = tblLabs.ID where tblLabs.LabName = CalibrationReview.CalLabName I hope this is clear as I can write this in code behind, but it'smuch better using sql simply because it's faster and only needs tobe run once. Inheriting databases and combining all of them to develop a large.Net management system is fun, huh? Thanks for any input, Zath
This is on Sybase but I'm guessing that the same situation would happen on SQL Server. (Please confirm if you know).
I'm looking at these new databases and I'm seeing code similar to this all over the place:
if not exists (select 1 from dbo.t1 where f1 = @p1) begin select @errno = @errno | 1 end
There's a unique clustered in dex on t1.f1.
The execution plan shows this for this statement:
FROM TABLE dbo.t1 EXISTS TABLE : nested iteration. Table Scan. Forward scan. Positioning at start of table.
It's not using my index!!!!!
It seems to be the case with EXISTS statements. Can anybody confirm?
I also hinted to use the index but it still didn't use it.
If the existence check really doesn't use the index, what's a good code alternative to this check?
I did this and it's working great but I wonder if there's a better alternative. I don't really like doing the SET ROWCOUNT 1 and then SET ROWCOUNT 0 thing. SELECT TOP 1 won't work on Sybase, :-(.
SET ROWCOUNT 1 SELECT @cnt = (SELECT 1 FROM dbo.t1 (index ix01) WHERE f1 = @p1 ) SET ROWCOUNT 0
hello friends my one insert code lines is below :) what does int32 mean ? AND WHAT IS DIFFERENT BETWEEN ONE CODE LINES AND SECOND CODE LINES :)Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString) Dim cmd As New SqlCommand("Insert into table1 (UserId) VALUES (@UserId)", conn) 'you should use sproc instead cmd.Parameters.AddWithValue("@UserId", textbox1.text) 'your value Try conn.Open()Dim rows As Int32 = cmd.ExecuteNonQuery() conn.Close()Trace.Write(String.Format("You have {0} rows inserted successfully!", rows.ToString())) Catch sex As SqlExceptionThrow sex Finally If conn.State <> Data.ConnectionState.Closed Then conn.Close() End If End Try MY SECOND INSERT CODE LINES IS BELOWDim SglDataSource2, yeni As New SqlDataSource() SglDataSource2.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString SglDataSource2.InsertCommandType = SqlDataSourceCommandType.Text SglDataSource2.InsertCommand = "INSERT INTO urunlistesi2 (kategori1) VALUES (@kategori1)" SglDataSource2.InsertParameters.Add("kategori1", kategoril1.Text)Dim rowsaffected As Integer = 0 Try rowsaffected = SglDataSource2.Insert()Catch ex As Exception Server.Transfer("yardim.aspx") Finally SglDataSource2 = Nothing End Try If rowsaffected <> 1 ThenServer.Transfer("yardim.aspx") ElseServer.Transfer("urunsat.aspx") End If
Hello, I am trying to create a table if one with the same name does not exists. My code is: Dim connectionString As String = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|PensionDistrict4.mdf;Integrated Security=True;User Instance=True" Dim sqlConnection As SqlConnection = New SqlConnection(connectionString) Dim newTable As String = "CREATE TABLE [" + titleString + "Comments" + "] (ID int NOT NULL PRIMARY KEY IDENTITY, Title varchar(100) NOT NULL, Name varchar(100) NOT NULL, Comment varchar(MAX) NOT NULL, Date datetime NOT NULL)" sqlConnection.Open() Dim sqlExists As String = "IF EXISTS (SELECT * FROM PensionDistrict4 WHERE name = '" + titleString + "Comments" + "')" Dim sqlCommand As New SqlCommand(newTable, sqlConnection) If sqlExists = True Then sqlCommand.Cancel() Else sqlCommand.ExecuteNonQuery() sqlConnection.Close() End If I keep getting a "Input String was incorrect format" for sqlExists? I am new to Transact-SQL statements, any help would be appreciated. Thanks Matt
ok i have 2 tables---one table is name CourseInformation with a field named Instructor and the data in there looks like this 'John Doe'. My other table Instructors has 3 fields InstructorName, LastName, FirstName. I am grabbing the Instructor field from CourseInformation and breaking up the names and inserting them into my instructors table as follows.. Insert into Instructors(InstructorName, LastName, FirstName) (Select Distinct ltrim(SUBSTRING(Instructor,CHARINDEX(' ',Instructor)+1,len(Instructor)))+', '+ SUBSTRING(Instructor,1,CHARINDEX(' ',Instructor)-1), ltrim(SUBSTRING(Instructor,CHARINDEX(' ',Instructor)+1,len(Instructor))) as LName, SUBSTRING(Instructor,1,CHARINDEX(' ',Instructor)-1) as FNamefrom CourseInformation where NOT EXISTS(Select * from instructors where LastName = LName and FirstName = FName) AND Instructor is not null)
Only problem is, I cant get the where not exists clause to work right(of course that wont work what i have cuz the LName and FName columns dont exist, i just did that for demo purposes). I dont want duplicate instructors in there..how can i accomplish this..is there a better way to rewrite my query? Any help is appreciated.
HI All,Which is best among the two 1) NOT IN or 2) NOT EXISTS .If the query is Select col1 from tab1 where col2 NOT IN (Select col 3 from tab2 where cl3=0) OR Select col1 from tab1 where col2 NOT EXISTS (Select col 3 from tab2 where cl3=0)
Hi, Is there any way to check whether a column is there in the table, if it is there i need to drop it through script.
i'm looking for the script, something like this..
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_Tbl_Product_Tbl_Products]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE [dbo].[Tbl_Product] DROP CONSTRAINT FK_Tbl_Product_Tbl_Products GO
In the same way i need to check for a column and drop it through script. Any help would be greatly appreciated. Thanks in advance.
Im having a problem with the following can anyone spot how i can fix it? I dont think it likes the begin statement but without it, it has a declare issue.
IF EXISTS (SELECT 1 FROM snapevent.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='FastEp_Snap_OD_Acc' + preports.dbo.f_filedate(getdate()) begin declare @CMD nvarchar(300) Set @CMD = 'drop table Snap_OD_Acc_' + preports.dbo.f_filedate(getdate()) --print @CMD exec (@CMD) end
The secenario is that, A application calls the SP with a parameter(login), and a string of datas ( Acctid level1 level2; Acctid level1 level2; .......)
UserID AcctID Level1 level2 test testee N Y
the SP have to get the first string of data and check if the Acctid exists or not. If yes then update else insert.Then get then the second string of data and check if the Acctid exists or not. If yes then update else insert.
After checking all the strings , it have to check if any Acctids other than acctid mentioned in the string exists in the table for that login, then delete those rows
I'm trying to perform an insert query on a table, but I also want to check to see if the record exists already in the table. It should be fairly simple, but I'm having a time of it. Should be something like:
select * from users u inner join miamiherald m on u.emailaddress = m.advertiseremail where not u.emailaddress not exists <<< (???)
If it does exist, I then want to retrieve two columns from it. HELP!!
The following works in SQL 2005 but NOT SQL 2005 Compact Edition:
IF EXISTS (SELECT ID FROM Court2 WHERE BookingDate = '2007-05-28') UPDATE Court2 SET T1100 = 52 WHERE (BookingDate = '2007-05-28') ELSE INSERT INTO Court2 (BookingDate,T1100) VALUES ('2007-05-28',52)
In CE I get the following error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 1,Token in error = IF ]
I can't find where the problem is - can someone help.
Dear all, i am trying to improve the performance of stored procedures and functions in that in key word is there i have to replace with exists.which one will give better performance.