The db that I took over is full of !@##$@, unnormalized tables, cursors, you name it and it has it :(.
There is this cursor that opens a temp table, fetches the key and then deletes from the production table using that key for every row in the temp table.
I want to change it to something like
delete from A where exists (select 1 from B where B.ID1 = A.ID1 and B.ID2 = A.ID2)
Now, I'm thinking that this query would secuentially scan A and compare the key to what B has and that is a waste of time. Is there a way to do it the other way around ? Scan the rows on table B and then delete them from table A ?
I haven't really played with sql in some time, maybe the answer is trivial but I can't see it right now.
Hi I have a weird problem I want to cursor thru the values in atemporary table and use the values to do a select statement to insertinto another temporary table...This select statement uses a like clausesomething like where....when I take off the insert still nothing comesback from the select...when I hardcode values it works...I getresults...is there something wrong with appending a +'%' to a valueread from a cursor???DECLARE @DEPT VARCHAR(65)SET @DEPT = "00201,00203"DECLARE @TB_ABSENCES TABLE(DeptOrEmpId VARCHAR(65))DECLARE @TB_DEPT TABLE ( V_DEPARTMENT_CODE VARCHAR(128) )INSERT INTO @TB_DEPT (V_DEPARTMENT_CODE)SELECT V_DEPT FROM [ISIS].[dbo].[FU_GET_DEPTS_FROM_STRING](',', @DEPT)DECLARE DEPTS CURSOR FAST_FORWARD FORSELECT V_DEPARTMENT_CODE+'%' FROM @TB_DEPTOPEN DEPTSFETCH NEXT FROM DEPTS INTO @DEPT_CODEWHILE @@FETCH_STATUS = 0BEGIN--INSERT INTO @TB_ABSENCES TABLESELECT Code from TB_EMPLOYEE_DEPARTMENT T2WHERE T2.V_HIERARCHY_CODE LIKE @DEPT_CODE + '%'FETCH NEXT FROM DEPTS INTO @DEPT_CODEENDCLOSE DEPTSDEALLOCATE DEPTS
Can one of you help me with using a cursor that would insert only 100 rows at a time from source table 1 to target table 2. I am not able to loop beyond the first 100 rows.
Here is what I have till now:
CREATE procedure Insert100RowsAtaTime AS SET NOCOUNT ON
declare @Col1 int declare @Col2 char(9) DECLARE @RETURNVALUE int DECLARE @ERRORMESSAGETXT varchar(510) DECLARE @ERRORNUM int DECLARE @LOCALROWCOUNT int
declare Insert_Cur cursor local fast_forward FOR SELECT top 100 Col1,Col2 from Table1 WHERE Col1 not in ( SELECT Col1 /* Col1 is PK. This statement is used to prevent the same rows from being inserted in Table 2*/ from Table2)
set @RETURNVALUE = 0 set @ERRORNUM = 0
BEGIN
open Insert_Cur fetch NEXT from Insert_Cur into @Col1, @Col2 while (@@FETCH_STATUS = 0) insert into Table2 (Col1,Col2) select @Col1,@Col2
SELECT @ERRORNUM = @@ERROR, @LOCALROWCOUNT = @@ROWCOUNT IF @ERRORNUM = 0 BEGIN IF @LOCALROWCOUNT >= 1 BEGIN SELECT @RETURNVALUE = 0 END ELSE BEGIN SELECT @RETURNVALUE = 1 RAISERROR ('INSERT FAILS',16, 1) END END ELSE BEGIN SELECT @ERRORMESSAGETXT = description FROM [master].[dbo].[sysmessages] WHERE error = @@ERROR RAISERROR (@ERRORMESSAGETXT, 16, 1) SELECT @RETURNVALUE = 1 END
I have stored procedure which contains follwing part of it. it says syntax when i worte line to get @@identity valuewhen delete that line command succesful. but i need to get @@identity from the insert statement and assign it to a variable and use it after any body pls tell me how to get this within a stored prosedure or what is the error of the following code bit. (#tblSalesOrders is a temporary table which containsset of records from orginal table )DECLARE @soNo1 INT DECLARE @CursorOrders CURSOR SET @CursorOrders = CURSOR FAST_FORWARD FOR select fldSoNo from #tblSalesOrders declare @newSONO1 int OPEN @CursorOrders FETCH NEXT FROM @CursorOrders INTO @soNo1 WHILE @@FETCH_STATUS = 0 BEGIN ----for each salesorder insert to salesorderline insert into tblSalesOrders (fldWebAccountNo,fldDescription,fldSoDate,fldGenStatus) select (fldWebAccountNo,fldDescription,fldSoDate,fldGenStatus) from #tblSalesOrders where fldSoNo =@soNo1;
set @newSONO1=SCOPE_IDENTITY; -------in this section again create another cursor for another set of records and insert to a table passing identity value return from the above insert -------------------------- SELECT @intErrorCode = @@ERRORIF (@intErrorCode <> 0) GOTO PROBLEM FETCH NEXT FROM @CursorOrders INTO @soNo1 END CLOSE @CursorOrders DEALLOCATE @CursorOrders
I have stored procedure .In SP i am using cursur to load data from Parent to several child table.
I have attached the script with this message.
And my problem is how to use direct select and insert or load to speedup the process instead of cursor.
USE [IconicMarketing] GO /****** Object: StoredProcedure [dbo].[SP_DMS_INVENTORY] Script Date: 3/6/2015 3:34:03 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO
Have two records getting inserted. All fields are identical except for cd_tp.
If 2 records are inserted I would like the record with cd_tp 3 deleted.
Code below doesn't seem to be working
delete orderrebate FROM OrderRebate inner join inserted on inserted.ord_type = OrderRebate.ord_type and inserted.ord_no = OrderRebate.ord_no and inserted.line_seq_no = OrderRebate.line_seq_no where inserted.ord_type = OrderRebate.ord_type and inserted.ord_no = OrderRebate.ord_no and inserted.line_seq_no = OrderRebate.line_seq_no and inserted.cd_tp = '3' END
Here's my sp. Before I insert my new values I want to delete the existing records from the table. Can I do this in the same sp ? If so, could someone tell me the syntax please.
Hi All, I have this project I'm working on it's Product Content Management System rewrite. I got to the point of updating the Product By Sku and not sure if I should use UPDATE statement or I should DELETE sections assosiated with the ProductContentID and then re-insert them again? I'm not sure which is more afficient? I can really do both and it's really not that complicated, the only problem I see with DELETE then INSERT is the ProductContentSectionId in the Sections table is going to grow very fast and I'm a bit concerned about it. We use SQL Server 2000 and we have about 4 bound tables where we keep the data. The one I'm talking about is the sections table where we keep the actual types of product content like a BoxShot, Description, Key Features and so on... Thank you in advance! Tatyana Hughes
hi all iwant to make feedback after insert data or delet date Like( the data is sucssfuly way) or(data is delete sucssuse way) but not alert iwant feedback thank you
hello all i have a problem in deleting and updating records when i configuring my data source i click on advanced button in the configuration datasource and then i check the two boxes to generate insert and update and optimistic concurrency but the problem is these two choices are not active unless there was a primary key in the table i have some tables doesnt have a primary key how i can fix that what should i do to allow insert and delete in these tables.thanks in advance
I am trying to update a SQL database with data from a Wang system. The Wang data is dumped to a txt file. I then import it into an update table in SQL via Access. Some of the data is new and some of the data is updated records. At this point I have been trying to create a script to update and add data to a table via the query tool in SQL Then delete data from the update table.
I was able to get the UPDATE and DELETE to work but I have not figured out how to insert new records at the same time? Can I use an IF statement? I will apreciate any help or sample code, Thanks.
UPDATE MemberList Set Name = NameUpd, Address1 = Address1Upd, Address2 = Address2Upd, City = CityUpd, State = StateUpd, ZipCode = ZipCodeUpd, MemberStatus = MemberstatusUpd FROM MemberList, MemberListUpd WHERE MemberList.MemberNumber = MemberListUpd.MemberNumberUpd
i am creating an insert based on a select statement -- i need to delete the row from the select statment table after it has been inserted
something like
insert into table_insert(value1, value2) (select table_exclude_id, value1, value2 from table exclude) delete from table_exclude where table_exclude_id in "the select statement"
I vaguely recall reading an article that I can no longer find that an update statement is executed as a combination of a Delete and an Insert by SQL server. Does anyone know if this a still a true statement in SQL Server 2005?
for now, doing a small school project, i find doing SPs for Insert useful, like checking for existing data and not inserting, that might not be the best method, i had advice from here i can use unique constraints instead, then what about update and delete? SPs also? the pros make SPs for everything? currently use dynamically generated SQL from SqlDataSources. for Update / delete. some delete are SPs too...
I have recently started an ASP.Net application and am having some issues updating, inserting and deleting rows. When I started working with it, I was getting errors because it could not find any update command. Eventually, I figured out how to automatically generate the commands, by configuring my SQLDataSource control and clicking the "advanced" button. Right now though, I have generated the commands, but I still can not insert, update or delete rows. When I attempt to update anything, I recieve an error that says "The data types text and nvarchar are incompatible in the equal to operator." Nowhere in my table do I have any rows that use the datatype "nvarchar", only "text" and "int". I tried switching all of my text columns to "nvarchar(500)", which did not help. I am led to believe that the auto generated SQL procedures are trying to do something behind the scenes that is making my database act up, because even when I delete rows, I get the same exception, so the datatypes cannot be messed up there, because all that the datasource is doing is deleting rows, therefore there is no need to worry about data types. I only get the error when I check the "Use optimistic concurrency" box. When I do not use optimistic concurrency, I can delete, insert, and update rows... but nothing happens. There are no errors, but nothing is deleted, updated or inserted either. Upon postback, nothing has changed. I may upload a copy of the exact exception page, if someone thinks that it may help. Here is the update command that was generated: UPDATE [Record Information] SET [Speed] = @Speed, [Recording Company] = @Recording_Company, [Year] = @Year, [Artist] = @Artist, [Side 1 Track Title] = @Side_1_Track_Title, [Side 1 Track Duration] = @Side_1_Track_Duration, [Side 2 Track Title] = @Side_2_Track_Title, [Side 2 Track Duration] = @Side_2_Track_Duration, [Sleeve Description] = @Sleeve_Description WHERE [Record Database ID] = @original_Record_Database_ID Apparently no stored procedures exist for any of these operations, and I am unsure why. The "Record Database ID" is my identity column, and is the only field that is (and is supposed to be) uneditable.
Hi, i want to create a sqldatasource in VWD also with advanced (insert, delete, update) option. This works fine for 'normal' tables, but when i try to do that with e.g. aspnet_roles table (indicated as vw_aspnet_Roles in dropdownlist of VWD), or aspnet_users table, that advanced option is not available, even when i select all fields. Why, and how can i solve that? Thanks Tartuffe
Hi,I just upgraded my ASP.NET 2.0 BETA 2 environment to the final release of ASP.NET 2.0 VWD.Once the update was finished, I could open my website without any problems..... Now, I noticed that in the final release, some modifications have been included in the Membership Stored Procedure and other stored procedures. So I created a new database (SQL Express) and added my data again.After re-creating my SQLDataSources, I tryed to enable the Editing and Deleting option in VWD and once I run my web application, it seems when selecting editing and then update, it doesn't work anymore....This is my code : <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:IMMOASPNETDBConnectionString %>" DeleteCommand="DELETE FROM aspnet_test WHERE (testID = @Original_testID)" SelectCommand="SELECT BuyID, BuyNL, BuyFR, Lastupdated FROM aspnet_Buy" UpdateCommand="UPDATE aspnet_Buy SET BuyNL = @BuyNL, BuyFR = @BuyFR WHERE (BuyNL = @original_BuyID)"> <DeleteParameters> <asp:Parameter Name="Original_testID" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="BuyNL" /> <asp:Parameter Name="BuyFR" /> <asp:Parameter Name="original_BuyID" /> </UpdateParameters> </asp:SqlDataSource> <br /> <br /> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="BuyID" DataSourceID="SqlDataSource1"> <Columns> <asp:CommandField ShowEditButton="True" /> <asp:BoundField DataField="BuyID" HeaderText="BuyID" InsertVisible="False" ReadOnly="True" SortExpression="BuyID" /> <asp:BoundField DataField="BuyNL" HeaderText="BuyNL" SortExpression="BuyNL" /> <asp:BoundField DataField="BuyFR" HeaderText="BuyFR" SortExpression="BuyFR" /> <asp:BoundField DataField="Lastupdated" HeaderText="Lastupdated" SortExpression="Lastupdated" /> </Columns> </asp:GridView>Can someone help me with this ? What is wrong with the Update command ?Thanks to all,Bart
I’m trying to create a sqlDataSource using the wizard, I can get the select statement, the here clause and the order by clause but when I click on the Advanced button the options to generate the insert, update and delete statements are not available. Does anyone know what am I doing wrong?
I've got four pages with in the first page a insert, in the second a select, in the thirth a update and in the fourth a delete statement. First the values of a textbox will be inserted in the database, then the values will be shown in labels and than it is possible to edit or delete the values inserted. Every inserted item belonging to each other has one ID. The follwing values has a second ID etc. How can I make that possible?? I think that I should pass the ID's between the pages so I'm sure that I edit or delete the values that I want. So insert value 1 in page 1, show with select value 1 in page 2, edit or delete value 1 in page 3 and 4. Maybe I didn't explain it good enough for you, please tell me then!! Thanks!!
I HAVE TWO TABLES IN THE DATABSE AND THE SECOND TALE SI FOR AUDITING. I WANT CREATE THE TRIGGER ON FIRST TABLE SO THAT I CAN PUT THE STATUS LIKE INSERT,UPDATE OR DELETE IN THE STATUS COLUMN IN SECOND TABLE. CAN SOMEBODY HELP IN WRITING THAT TRIGGER..? HOW CAN I DETERMINE WAETHER THE RECORD IS BEEN INSERTED OR UPDATED OR DELETED.
DO I HAVE TO WRITE A SEPERATE TRIGGER FOR EACH ACTIVITY..OR I CAN WRITE IT IN THE SINGLE TRIGGER..?
I am having problems with a trigger that is designed to audit changes to a particular field in a table. If that field is updated, then the old record is inserted into an audit table.
This trigger never fails when I run test data against it from Query Analyzer. It works some of the time when the web application updates it, fails other times.
Typically, multiple records are updated at the same time. Any ideas?
Here is the Trigger:
create trigger t_u_product_rate_detail on product_rate_detail for insert, update, delete
--Set values so function isn't executed a bunch of times select @auditdate = getdate(), @audituser = suser_sname()
if exists (select * from inserted) begin if exists (select * from deleted) begin insert into product_rate_detail_audit_log select d.product_rate_detail_id, d.product_rate_id, d.day_of_week_id, d.ad_size_id, d.rate, d.plan_vol, d.plan_freq, @auditdate, @audituser, 'U' from deleted d join inserted i on i.product_rate_detail_id = d.product_Rate_detail_id where (d.rate <> 0 and d.rate is not null) and i.rate <> d.rate -- this determines if the rate has changed. end end
GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO
Howdy all. I opened a 200 mb. file in Query Analyzer that is full of Inserts/ Updates/ and Deletes. I tried just to parse it, and killed it after 18 hours. There is no blocking. All of the appropriate indexes exist. I even removed them and retried JIC. The box is plenty powerful for this task. Does anyone have any ideas? I've tried several times with no luck. At the top of the file is SET IMPLICIT_TRANSACTIONS ON and then every 10,000 statements is COMMIT WORK. I've tried adjusting the number of commits to a lower number with no luck. This works fine on smaller files (3 - 20 mb).
How to Insert,Update and delete through script without using merge.I have simple requirement of Deleting,Inserting and Update from one table to other table...Here is the Sample Data
CREATE TABLE #Table1 (ID INT ,Name VARCHAR(30),DATEKEY INT) INSERT INTO #Table1 (ID,Name,DATEKEY)VALUES (1,'Mohan',20131231) INSERT INTO #Table1 (ID,Name,DATEKEY)VALUES (2,'Raj',20131231) INSERT INTO #Table1 (ID,Name,DATEKEY)VALUES (3,'Majja',20131231) INSERT INTO #Table1 (ID,Name,DATEKEY)VALUES (4,'Majjaa',20131231)
[code]...
So now i need to update 1st record and add another new record..So i need to update as well as delete the existing data in Target table.
INSERT INTO #Table1 (ID,Name,DATEKEY)VALUES (5,'Macha',20131231)
My output should come like this one :
IDNameDATEKEY 1Mohan20131231 5Macha 20131231
with out using merge how can i handle Update,insert and Delete through TSQL
I have to create a trigger that will log who changed information on a table and when (NOT what they have changed).
My idea is to get the users name and see if it is in a table if not create it and get the associated ID, also get the ID of table that was accessed along with the ID of the type of task that was performed. Take this data and insert it into a table.
hi, how can I use stored proc to delete all rows from a table (table1) and insert new ones. for instance. my query is: ------------------------------------- select field1, two, three from table1 innerjoin table2 on etc... where condition1 and condition2 ------------------------------------- I want to place the result in my table (table1) and everything I run the stored pro I want to delete the content and place the new dataset in the table1?
I hope I'm clear what I'm trying to do. thank you very much in advance. P.S please be detailed when explaining.