MS SQL Server Trigger if else insert - sql

I'm trying to write a trigger but I need help. How can I write this type of trigger?
If data coming null insert into this parameter?
There is my codes
CREATE TRIGGER AddDayOn ON Control
INSTEAD OF INSERT
AS
DECLARE #first DATETIME,#second DATETIME,#name NVARCHAR(11),#birth DATETIME
SELECT #first = First,
#second = Second,
#name = Name,
#birth = Birth
FROM inserted
INSERT INTO Control(
Name,
First,
Birth,
Second,
Prob
)
VALUES
( #name,
#first,
#birth,
DATEADD(DAY,220,#first),
DATEADD(DAY 250,#first))
I need to chance this trigger with if-else.Because i have 3 more parameters(Four,Five,Six). I'm try to write something like that
If #first not null DATEADD..
If #four not null DATEADD.. like that

you can use exists in your statement like this:
insert into table1(col1,col2)
select col1,col2 from inserted as i
where not exists(select 0 from table1 where relatedkey=i.relatedkey)

Related

Can I put an INSERT inside an INSTEAD OF INSERT trigger in SQL Server?

I'm having a some troubles with a complicated query, that required me to insert something in a table, but if I found that two columns are the same I should stop the transaction with a trigger. I make some code to do that, but I'm not sure 100% of it even when it works fine now.
alter trigger TR1
on Passer instead of insert
as
begin
declare #A int
declare #B int
declare #C int
set #A = (select code_ligne from inserted)
set #B = (select ordre_passage from inserted)
set #C = (select code_ville from inserted)
select * from passer
where code_ligne = #A
and ordre_passage = #B
if(##rowcount = 0 )
begin
insert into Passer values(#A,#C,#B)
print 'okay'
print ##rowcount
end
end
When you have scalar variables like this in a trigger you are going to run into problems. If you have two rows inserted at once you will only get 1 row inserted into Passer. You don't need these variables at all. Just switch this around to be a single set based insert statement. Something along these lines.
alter trigger TR1 on Passer instead of insert as
begin
insert into Passer
(
code_ligne
, ordre_passage
, code_ville
)
select i.code_ligne
, i.ordre_passage
, i.code_ville
from inserted i
join Passer p on p.code_ligne = i.code_ligne
and p.ordre_passage = i.ordre_passage
if(##rowcount = 0 ) begin
print 'okay'
print ##rowcount
end
end

Create a trigger in sql server after a column is update to specified value

i need to create a trigger that do this action:
If the column "idStatoTicket" is update to the value "3" i've to set another column ("dataChiusura") to the current timestamp.
I've tryed this
CREATE TRIGGER Customer_UPDATE
ON TICKET
FOR UPDATE
AS
BEGIN
DECLARE #dataChiusura datetime
IF UPDATE(idStatoTicket = 3)
BEGIN
SET #dataChiusura = CURRENT_TIMESTAMP
END
INSERT INTO TICKET(dataChiusura)
VALUES(#dataChiusura)
END
Some Help?
You should use the INSERTED data set to check for the value. Please try something like that:
if exists (
select * from INSERTED where idStatoTicket = 3
)
begin
SET #dataChiusura = CURRENT_TIMESTAMP
end
You need to join the INSERTED to your original table to be able to change the value to what you want it to be.
Here is a working example for you:
Drop Table MyTable
GO
Create Table MyTable
(
Id Int Identity (1, 1),
Value VarChar (100),
idStatoTicket Int,
DataChiusura DateTime
)
GO
Insert Into MyTable Values ('Test 1', 1, GetDate())
Insert Into MyTable Values ('Test 2', 3, GetDate()-1)
Select * From MyTable
GO
Create Trigger MyTable_Update ON MyTable FOR Update
as
Begin
Update T
Set DataChiusura = GetDate()
From MyTable T
Inner Join Inserted i
On T.Id = i.id
And i.idStatoTicket = 3
End
GO
Update MyTable Set Value = 'Test 22' Where Value = 'Test 2'
Select * From MyTable
I'm not an expert but you seem to do separate insert not related to the row being updated and you probably end up with an empty row with just dataChiusura set ..

Collect id's of ALL inserted records as result set

I need a stored procedure which returns resultset of IDs for created records. I've already read that SCOPE_IDENTITY gives only last ID. but my SQL skill is not enough to solve this particular case and get all IDs as the output.
here's what I have for now - this only gets the last record's id
USE AdventureWorks2008;
DELETE FROM [HumanResources].[Shift] where [HumanResources].[Shift].Name='c' or [HumanResources].[Shift].Name='d'
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'ShiftUpdateXml')
DROP PROCEDURE ShiftUpdateXml
GO
CREATE PROCEDURE ShiftUpdateXml
#strXML XML, #ShiftID [tinyint] = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT [HumanResources].[Shift](Name,StartTime,EndTime) SELECT
TEMP.Name,TEMP.StartTime,TEMP.EndTime
FROM (SELECT
assignreassignro.value('Name[1]','nvarchar(50)') AS Name,
assignreassignro.value('StartTime[1]','time(7)') AS StartTime,
assignreassignro.value('EndTime[1]','time(7)') AS EndTime
FROM #strXML.nodes('documentelement/assignreassignro')Documentelement(assignreassignro)) AS TEMP
SET #ShiftID = SCOPE_IDENTITY();
END
GO
DECLARE #ShiftID INT;
DECLARE #XmlVal XML= '<?xml version="1.0"?>
<documentelement>
<assignreassignro>
<Name>c</Name>
<StartTime>10:30:00.0000000</StartTime>
<EndTime>17:30:00.0000000</EndTime>
</assignreassignro>
<assignreassignro>
<Name>d</Name>
<StartTime>11:00:00.0000000</StartTime>
<EndTime>18:00:00.0000000</EndTime>
</assignreassignro>
</documentelement>'
EXEC ShiftUpdateXml #XmlVal,#ShiftID = #ShiftID OUTPUT;
PRINT #ShiftID;
You are looking for the output clause. If you just want the ids, you can do:
DECLARE #ids TABLE (id int);
INSERT [HumanResources].[Shift](Name,StartTime,EndTime)
OUTPUT inserted.Id INTO #ids
SELECT assignreassignro.value('Name[1]', 'nvarchar(50)') AS Name,
assignreassignro.value('StartTime[1]', 'time(7)') AS StartTime,
assignreassignro.value('EndTime[1]', 'time(7)') AS EndTime
FROM #strXML.nodes('documentelement/assignreassignro') Documentelement(assignreassignro);
If you want additional values, you can add them to the table and the INSERT statement.
Also, note that you do not need a subquery for the SELECT.
To get multiple rows you'll need to use output from the table inserted with something like this:
CREATE PROCEDURE ShiftUpdateXml
#strXML XML
AS
BEGIN
INSERT [Shift](Name,StartTime,EndTime)
output inserted.id
SELECT
TEMP.Name,TEMP.StartTime,TEMP.EndTime
FROM (SELECT
assignreassignro.value('Name[1]','nvarchar(50)') AS Name,
assignreassignro.value('StartTime[1]','time(7)') AS StartTime,
assignreassignro.value('EndTime[1]','time(7)') AS EndTime
FROM #strXML.nodes('documentelement/assignreassignro')Documentelement(assignreassignro)) AS TEMP
END
That way the procedure will return the list of IDs. I made an example into SQL Fiddle

How to insert leading zero in SQL Server

This is the code for selecting with leading zeros:
SELECT RIGHT('00000'+ CONVERT(VARCHAR,Asset_No),6)
FROM schemaAsset.SystemDefined
How can I insert a value to the column Asset_no with leading zeros?
Example is I am only inserting "1" to the column Asset_no, but in the code, it will insert "000001". And also when I insert two digits like 26, it will insert as "000026". The length does not change. Is this possible in SQL Server?
One way to do this is with an INSTEAD OF trigger.
USE tempdb;
GO
CREATE TABLE dbo.whatever
(
Asset_No VARCHAR(6)
);
GO
CREATE TRIGGER dbo.fix_whatever
ON dbo.whatever
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.whatever(Asset_No /*, other columns */)
SELECT RIGHT('000000' + CONVERT(VARCHAR(6), Asset_No), 6)
/*, other columns */
FROM inserted;
END
GO
INSERT dbo.whatever(Asset_No) SELECT '22';
GO
SELECT Asset_No FROM dbo.whatever;
GO
Results:
Asset_No
--------
000022
If you want to do the padding in SQL Server, you can do something like this with your INSERT statement:
DECLARE #Asset_no INT = 12;
INSERT INTO schemaAsset.SystemDefined (Asset_no)
SELECT RIGHT('00000'+ CONVERT(VARCHAR(6),#Asset_No),6)
The script below allows you to populate a column with numbers for every row in the table. This will give you numbers starting at 2000. The first entry would be 0002000.
Declare #id varchar(15)
set #id = '1999'
update sometable
set #id = id = replace(STR(#id + 1,7),' ', '0')
go
For Oracle:
lpad(cast(NUMERIC_VAR as VARCHAR2(5 BYTE)),5,'00000')

Update and Insert Stored Procedure

I want to create a stored procedure that performs insert or update operation on a column if
that column does not contains a value that already exists in database it should allow insert when COUNT(field) = 0 or update when COUNT(field)=0 or 1 And I should know that either of these operation is performed or not.
Please solve my problem using COUNT not Exists because that won't work for UPDATE.
I am working in ASP.net - I have two columns of a table that are needed to be kept unique without using the unique constraint. So I want a procedure like this:
create proc usp_checkall #field1 varchar(20),
#field2 varchar(20),
#ID int,
#count int output
Now your query on updating/inserting #field1 & #field2 on basis of #id
If you happen to have SQL Server 2008, you could also try:
MERGE dbo.SomeTable AS target
USING (SELECT #ID, #Field_1, #Field_2) AS source (ID, Field_1, Field_2)
ON (target.ID = source.ID)
WHEN MATCHED THEN
UPDATE SET Field_1 = source.Field_1, Field_2 = source.Field_2
WHEN NOT MATCHED THEN
INSERT (ID, Field_1, Field_2)
VALUES (source.ID, source.Field_1, source.Field_2)
Use:
INSERT INTO your_table
(column)
VALUES
([ your_value ])
WHERE NOT EXISTS (SELECT NULL
FROM your_table
WHERE t.column = [ your_value ])
That will work on SQL Server, MySQL, Oracle, Postgres. All that's needed is to use the db appropriate variable reference. IE: For MySQL & SQL Server:
INSERT INTO your_table
(column)
VALUES
( #your_value )
WHERE NOT EXISTS (SELECT NULL
FROM your_table
WHERE t.column = #your_value)
To see if anything was inserted, get the value based on ##ROWCOUNT if using SQL Server. Use SQL%ROWCOUNT if you are using Oracle.
if Exists select * from Yourtable WHere Your Criteria
begin
update ...
end
else
begin
insert ...
end
This kind of approach will do the trick. #AlreadyExisted could be an OUTPUT parameter on the sproc for your calling code to check once it's returned.
DECLARE #AlreadyExisted BIT
SET #AlreadyExisted = 0
IF EXISTS(SELECT * FROM YourTable WHERE YourField = #FieldValue)
BEGIN
-- Record already exists
SET #AlreadyExisted = 1
UPDATE YourTable
SET....
WHERE YourField = #FieldValue
END
ELSE
BEGIN
-- Record does not already exist
INSERT YourTable (YourField,....) VALUES (#FieldValue,.....)
END