SQL Server Express Stored procedure: Select, delete, insert - sql

I am using below query to insert record into a table.
DELETE FROM Table1;
INSERT into Table1 (F1,f2,f3...) SELECT * FROM TABLE2 WHERE......
The problem is, SELECT query took some time to fetch due to many conditions, while records are already deleted from Table1, live records may not be available for display in Client Side while waiting for SELECT query result and be inserted in table1.
I need to SELECT record first, then DELETE record from the table1, then insert the selected record to table1. Can anyone help me please?

you can use transaction like and also delete after insert but add somewhere criteria.
BEGIN TRY
BEGIN TRAN
While (i<0)(while loop and so on condition.)
BEGIN
DELETE FROM Table1 ;
INSERT into Table1 (F1,f2,f3...) SELECT * FROM TABLE2 WHERE......
END
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH

You can use ##rowcount
Declare #row_count int
SELECT #row_count=count(*) FROM TABLE2 WHERE......
INSERT into Table1 (F1,f2,f3...) SELECT * FROM TABLE2 WHERE......
DELETE TOP(#row_count) FROM Table1 ;
First get count how many records you want to insert the,
First data is inserted,
if data insertion success then data is delete
other wise data won't be delete
So, every time data is available in table to show client

Related

Trigger to delete prior duplicate records in the table

I need to write a trigger based on the following condition
Before inserting a record in the table, I need to compare the value of one column to the existing records, and if records found then I need to delete those records having same column value in the already existing records, and then need to insert that new record.
Please let me know how to achieve this.
Thanks
CREATE TRIGGER [dbo].[CustomInsert_Trigger] ON [dbo].[Realtimebookingcount]
INSTEAD OF INSERT AS
BEGIN
DECLARE #Flag INT
SELECT #Flag = Booking_NUM FROM inserted
IF (SELECT COUNT(1) FROM Realtimebookingcount
WHERE Booking_NUM = #Flag) > 0
BEGIN
DELETE FROM Realtimebookingcount
WHERE Realtimebookingcount.Booking_NUM = #Flag
END
INSERT INTO Realtimebookingcount
SELECT * FROM inserted
END

After insert not working

all id columns has auto_increment
In my trigger:
ALTER trigger [dbo].[mytrig]
on [dbo].[requests]
after INSERT, UPDATE
as
begin
declare #MyId1 int
set #MyId1 = (select Id from inserted)
declare #MyId2 int
declare #MyId3 int
if (select column1 from inserted) = 1
begin
insert into [dbo].[contracts] select column1,column2,column3 .... from inserted
set #MyId2 = SCOPE_IDENTITY()
insert into [dbo].[History] select column1,column2,column3 .... from inserted
set #MyId3 = SCOPE_IDENTITY()
insert into [dbo].[contracts_depts](Id_Contract ,column5) select #MyId2,column6 from request_depts where Id_request=#MyId1
insert into [dbo].[History_depts] (Id_InHistory,column5) select #MyId3,column6 from request_depts where Id_request=#MyId1
end
end
#MyId1 returns value only after update but not after insert. Do I have to use scope_identity() or something ?
Your main issue is: you're assuming the triggers is called once per row - that is NOT the case!
The trigger is called once per statement, and if your statement affects multiple rows, the Inserted pseudo table will contain multiple rows - so your statement here
set #MyId1 = (select Id from inserted)
really isn't going to work - it will select one arbitrary row (out of however many there are).
You'll need to rewrite your trigger to take this fact into account! Assume that Inserted contains 100 rows - how do you want to deal with that? What are you trying to achieve? Triggers don't return values - they will record into an audit table, or update other rows, or something like that ....

Multiple delete operation in a stored procedure

I want to make some tables empty if a stored procedure runs but I couldn't do that. What I did is
create proc MakeEmpty ()
as
begin
delete from table1
delete from table2
delete from table3
end
Use truncate instead and remove the () like this:
create proc MakeEmpty
as
begin
truncate table table1
truncate table table2
truncate table table3
end
Two things:
1 - Those parentheses should only be used if you are declaring a parameter for the procedure. If there is no param they are unneeded.
2 - If you want to empty the tables, then you should use TRUNCATE - it's minimally logged and is basically a meta-operation instead of a row-by-row delete.
You will need to clarify about what's not working, but something like this should do the trick:
BEGIN
IF EXISTS (SELECT 1 from DatabaseName.sys.Tables WHERE Name = 'Table1')
TRUNCATE TABLE Databasename.dbo.Table1
...repeat for other tables...
END
Try to remove the ( and )
create proc MakeEmpty
as
begin
delete from table1;
delete from table2;
delete from table3;
end
but make sure table2 and table3 does not reference table1 and table3 does not reference table2

How to insert all records of a table in another table using a stored procedure

I got a table with approx 13066 records in which I want to add all other records from another table (having approx. 1346 records). There is a stored procedure which does the insert and I want to use it for all records to be inserted. Can anyone please help?
It is this simple unless you haven't given all information, such as "there are duplicates" or "only if not already there"
CREATE PROC DoSomething
AS
SET NOCOUNT ON
INSERT table1 (col1, col2, etc)
SELECT col1, col2, etc FROM table2
GO
Edit:
There is something missing.
OP wants a loop through table2 to be able to call an existing stored procedure
To do it properly you'd use
INSERT table1 (col1, col2, etc)
SELECT col1, col2, etc FROM table2 t2
WHERE NOT EXISTS (SELECT * FROM table1 t1
WHERE t1.key = t2.key and <some conditions>)
I may have misinterpreted your question but it seems like that you want to execute a stored procedure and insert the results of the stored procedure in to your main table.
To do this you can do:
INSERT INTO dbo.YourMainTable
EXEC dbo.YourStoredProcedureName
EDIT:
The only way I can think of doing this would be to use a cursor.
DECLARE #PrimaryKeyFieldInTable2 int
DECLARE spCur CURSOR LOCAL FOR
SELECT PrimaryKetCol From Table2
OPEN spCur
FETCH NEXT FROM spCur INTO #PrimaryKeyFieldInTable2
WHILE ##FETCH_STATUS = 0 BEGIN
INSERT INTO dbo.Table1
EXEC dbo.YourStoredProceudre #PrimaryKeyFieldInTable2
FETCH NEXT FROM spCur INTO #PrimaryKeyFieldInTable2
END
CLOSE spCur
DEALLOCATE spCur
This assumes that your Stored Procedure accepts one parameter to select each row from Table2.
This isn't the best use of SQL Server but if you really must do it this way then I can't think of any other way.

SQL Trigger - How do I test for the operation?

My trigger fires on INSERT, UPDATE and DELETE. I need to insert from the appropriate in memory table (inserted, deleted) depending upon which operation triggered the trigger. Since only inserted is populated on INSERT or deleted on DELETE I figure I can just do an insert and if there's no rows and I'm good.
But, UPDATE populates both tables. I only want the values from deleted on UPDATE. I tried testing for update using UPDATE(column) function, but this returns TRUE even on INSERT. So, how can I test for UPDATE?
ALTER TRIGGER CREATE_tableAudit
ON dbo.table
FOR INSERT, UPDATE, DELETE
AS
BEGIN
IF(UPDATE([column1]))--returns true on INSERT :(
BEGIN
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
SELECT * from deleted --update
END
ELSE
BEGIN
--only inserted is populated on INSERT, visa-versa with DELETE
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from inserted --insert
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from deleted --delete
END
To test for UPDATE, look for identical primary key values in both the Inserted and Deleted tables.
/* These rows have been updated */
SELECT i.PKColumn
FROM inserted i
INNER JOIN deleted d
ON i.PKColumn = d.PKColumn
Assuming that the primary keys of rows didn't change, you can find updated rows by joining the Inserted and Deleted tables on the primary key field(s). If joining these two tables produces rows, then you can safely assume that those rows were updated.
If an update does change the primary key of a row, then you're probably better off just treating it as two operations, a delete and an insert.
The following has been useful to in triggers:
The * in the queries could be changed to include only fields you want to have compared; could exclude the autonumber if it changes in the source table.
To check for Inserted:
if exists (Select * from inserted) and not exists(Select * from deleted)
begin
...
end
To check for Updated:
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
...
end
To check for Deleted:
if exists(select * from deleted) and not exists(Select * from inserted)
begin
...
end