How to automate SQL queries to avoid manually executing it everytime - sql

I have a set of SQL queries that has some dynamic values in it. Every time I need to manually update those dynamic values and ask the DB team to run those SQL queries. For example, in the below set of SQL queries, values such as 1001, WASTE MANAGEMENT, WASTE MANAGEMENT_SUB, 3846333 are dynamic values that need to be modified for a different set of values. I am looking for a way to write some stored procedures so that these values can be added dynamically and execute that procedure to insert into DB. I am basically a UI developer and new to automating SQL queries. Please correct me if my understanding is wrong. Any help or tips on any alternate solutions are appreciated. Any help on how to achieve my understanding is also highly appreciated. Thanks in advance.
INSERT INTO TEMP_BILLERS values('1001','WASTE MANAGEMENT','WASTE MANAGEMENT','WASTE MANAGEMENT_SUB','3846333');
INSERT INTO TBL_FP_BILLER_HEADER(BILLER_NAME)
SELECT UNIQUE(biller_name)
FROM temp_billers
WHERE cif IN ('3846333')
ORDER BY biller_name asc;
INSERT INTO TBL_FP_BILLER_DETAIL(biller_id, cif, service_id, service_name, account_number)
SELECT tblh.biller_id, tbltemp.cif, tbltemp.acc_num, tbltemp.service_name, tbltemp.acc_num
FROM TBL_FP_BILLER_HEADER tblh
INNER JOIN TEMP_BILLERS tbltemp
on tblh.biller_name=tbltemp.biller_name
where tbltemp.cif='3846333';
UPDATE TBL_FP_BILLER_DETAIL
SET PAYMENT_TYPE='A'
,REF_RETENTION_POLICY='90'
, REF_EXPIRATION_POLICY='7'
WHERE CIF='';
Insert into TBL_FP_USER_DEFAULT_BILLER (BILLER_ID,BILLER_NAME,CREATED_DATE,CREATED_BY,MODIFIED_DATE,MODIFIED_BY)
select c.biller_id,'WASTE MANAGEMENT',null,null,null,null
from TBL_FP_BILLER_DETAIL c
where cif='3846333';
COMMIT;

it should be something like:
create procedure example (#ttt nvarchar(100), #ddd nvarchar(100) as
BEGIN
insert into sometable
select something
where somecolumn = #ttt
END
You should create procedure that get required parameters, and then use them in your queries.

Related

Triggers in SQL

I am having trouble with the following problem, Just wondering if you could give me any guidance on how i would start this.
Write a trigger to capture an input before it's inserted into a table
so that the value of the insert will be modified to be appended with
the text -previous
Say I have a table called StaffDetails and i could insert info such as ID, How would i apply it to the above problem.
Thank You
Create Trigger trg_name
on StaffDetails
instead of insert
referencing new as new_row
as
begin
#new_row.ID = (#new_row.ID + '_previous')
insert into StaffDetails (.....) values (#new_row.ID, .....)
end
it would probably look something like this, maybe youll have to change some syntax because its not the same for mysql and sql server, for detailed information on syntax for sql server you can look at https://msdn.microsoft.com/en-us/library/ms189799.aspx

How to update and insert in T-SQL in one query

I have a database that needs from time to time an update.
It may also happens that there are new data while the update runs.
In MySQL there is a option
INSERT INTO IGNORE
I can't find something like this in T-SQL.
No Problem to update ID 1-4 but then there is a new record for ID 5.
The UPDATE query don't work here.
And when I try to INSERT all data again I get a DUPLICATE KEY error.
Additional Infos:
I've forgotten to say that my data come from external sources. I call an API to get data from it. From there I have to insert these data into my database.
I have to admit that I don't understand MERGE. So my solution for now is to use TRUNCATE first and then insert all data again.
Not the best solution but MERGE works, so far I understand it, with two tables. But I have only one table. And to create a table temporarly to use MERGE and later drop that table is in my eyes a bit to much for my little table with 200 records in it.
You can use MERGE keyword. Basically, you need to specify the column(s) on which to join the source of data with target table, and depending on whether it is matching (existing record) or not matching (new record), you run an UPDATE or INSERT.
Reference: http://msdn.microsoft.com/en-us/library/bb510625.aspx
Is a stored procedure an option?
CREATE PROCEDURE dbo.Testing (#ID int, #Field1 varchar(20))
AS
BEGIN
UPDATE tblTesting
SET Field1 = #Field1
WHERE ID = #ID
IF ##ROWCOUNT = 0
INSERT INTO tblTesting (ID, Field1) SELECT #ID, #Field1
END

Updates on a table must be inserted into another table

Is there a way to insert records into TABLE B if there is an update in TABLE A?
I don't want to use triggers.
The answer is we can use the OUTPUT clause of instead of triggers:
USE AdventureWorks2012;
GO
IF OBJECT_ID('dbo.vw_ScrapReason','V') IS NOT NULL
DROP VIEW dbo.vw_ScrapReason;
GO
CREATE VIEW dbo.vw_ScrapReason
AS (SELECT ScrapReasonID, Name, ModifiedDate
FROM Production.ScrapReason);
GO
CREATE TRIGGER dbo.io_ScrapReason
ON dbo.vw_ScrapReason
INSTEAD OF INSERT
AS
BEGIN
--ScrapReasonID is not specified in the list of columns to be inserted
--because it is an IDENTITY column.
INSERT INTO Production.ScrapReason (Name, ModifiedDate)
OUTPUT INSERTED.ScrapReasonID, INSERTED.Name,
INSERTED.ModifiedDate
SELECT Name, getdate()
FROM inserted;
END
GO
INSERT vw_ScrapReason (ScrapReasonID, Name, ModifiedDate)
VALUES (99, N'My scrap reason','20030404');
GO
The mechanism for doing this is called triggers.
Saying that you want to do this but don't want to use triggers is like saying you want to see the Eiffel Tower, but you don't want to go to France.
You could, I suppose, write a stored procedure that does all the logic that would have been in the trigger, if you can ensure that all data updates will be via that stored procedure.
If you don't want to use triggers, then you would have three options.
The first would be to wrap all inserts/updates/deletes in stored procedures. Then use only these stored procedures for data modification. This is actually the approach that I generally take.
Another would be to have a process that runs periodically looking for changes to the data. This is actually hard to do for updates. It is pretty easy to do for inserts because you can add an column with a default creation date, so you can readily find what has recently been added.
The third way is to use SQL Server Change Tracking (see here).
You could make a stored procedure that performs both the update in table A and the insert in table B
CREATE PROCEDURE proc_name
#id
#param1
AS
BEGIN
update tableA
set field1 = #param1
where ID = #id
insert into tableB(field1)
values(#param1)
END

Insert into table stored procedure results plus variable

I need to insert into a table the results of a stored procedure(SP) plus a couple of other variables.
I know how to insert the SP results but not the variables as well. Is there a way I can do this without having to write a separate update query or pass/return the variable into the SP.
I.e.
INSERT INTO contacttable(name, address, telnum)
EXEC GetContactDetails #ContactId
UPDATE contacttable SET linkId = #LinkId where id = #ContactId
Can I pass the #linkId variable into the INSERT in anyway rather than having to do the separate update?
Thanks.
You can't do this the way you explain your current scenario is.
You either modify the proc to receive the extra parameter and you return it from there so that the insert statements already has this parameter, or you continue doing what you are doing.
Another possibility would be to change that proc into a table-valued function in a way that you can specifically select the columns you need from the resultset and you add the extra parameter in the insert. Something like:
INSERT INTO contacttable(name, address, telnum,linkid)
select name, address,telnum,#linkid from fnGetContactDetails(#ContactID)

SQL Stored Proc: Help converting to trigger

I'd like to convert a stored proc into a trigger. The stored proc is supposed to be run after inserts/updates, but users forget to execute it more often than not!
The stored proc inserts recalculated values for some rows:
--Delete rows where RowCode=111
DELETE FROM dbo.TableA WHERE [year]>=1998 AND RowCode=111
--Insert new values for RowCode=111 for years>=1998
INSERT INTO dbo.TableA
SELECT [Year], RowCode=111, ColCode, SUM(Amt) AS Amt
FROM dbo.TableA
WHERE [Year]>=1998 AND RowCode IN (1,12,23) AND ColCode=14
GROUP BY [Year], ColCode
I'd like to put this into a trigger so that the users don't have to think about running a procedure.
I have the following started, but I'm not sure if i'm on the right track. Should I be using FOR, AFTER or INSTEAD OF?
CREATE TRIGGER TRIU_TableA
ON TableA
FOR INSERT,UPDATE AS
BEGIN
SET NOCOUNT ON
IF EXISTS (SELECT * FROM Inserted WHERE RowCode=111)
BEGIN
INSERT INTO TableA
SELECT [Year], RowCode, ColCode, SUM(Amt) AS Amt
FROM Inserted
WHERE [Year]>=1998 AND RowCode IN (1,12,23) AND ColCode=14
GROUP BY [Year], ColCode
END
END
Any help on how to go about this would be very much appreciated.
Many thanks
Mark
You forgot the delete part.
But why doesn't your application just run the existing proc automatically after every insert/update? Are people updating your database from a query window?
Make it an AFter trigger, After and For are the same, but after is the newer syntax.
You should be using FOR
Comparing the Trigger to the Stored Proc it all looks fine.
What other problems do you have?