SQL After Insert Trigger - Insert values from Select Statement [closed] - sql-server

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In my database I have one table which when there is a record inserted into it a trigger will use information from the data inserted, run a select statement on the rest of the database, and insert the result into another database on the same server.
Ive never written a trigger before and Im not entirely sure that the examples out there help a lot.
Thanks in advance

its always good to start learning ...here is some sample code and some links to start ..
create trigger <<give your triggername>>
on
<<give your tablename>>
after insert
as
begin
select * from inserted--gives me data inserted
--run on rest of database--your logic goes here
select * from inserted i
join
some table tbl
on
tbl.id=i.id
insert into anotherdatabase.dbo.anotherdatabasetable
select * from inserted
end
Also please be aware that ,if the above trigger fails due to some reason ,your insert also will be rolled back..
some good links:
http://www.sqlteam.com/article/an-introduction-to-triggers-part-i
Insert Update trigger how to determine if insert or update
sql server trigger

Related

Why is SQL Server cutting of first four letters of a column name? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 23 days ago.
Improve this question
SQL Server is returning unexpected results from a similarly named table.
This one has me puzzled. Selecting column names from sys.columns and the GUI indicate the column name is attachmentid. However the statement
select attachmentid from attachment
generates an error
Invalid column name 'attachmentid'
The statement
select * from attachment
returns a column named fileattachmentid instead. So I did a little exploration and found that there's also a table called fileattachment. It seems that SQL Server is returning the results from the fileattachment table instead of attachment.
Wrapping the table name in double quotes does not solve the issue. They are both in the same schema. The only thing I can think of is the word "file" is restricted and SQL server is mis-selecting the table somehow. Any ideas?
I am going to take this to our Microsoft Support plan, I have a feeling this may be happening from the database being the backend for a Microsoft Dynamics 365 application. That or SQL Server is stripping out the reserved keyword "file" from the fileattachments table, and since it has the lower objectid, its getting returned first when it goes hunting for the attachment table.
To sum up the suggested reasons for this issue:
I am in the wrong database (I am not as there is only one SQL Server database I have ever connected to and I can only see one database listed in the GUI)
I am swapping connections (I am not as this is the only connection I have ever made in SSMS on this machine)
I have multiple schemas (There is only one schema according to sys.schemas...dbo)
4.Someone is modifying the tables,columns,etc. (that would be concerning since I am the only developer on staff and wouldnt explain how the column/table names remain the same after refreshing the GUI repeatedly)
It could be a view (there are no views in the database, attachment and fileattachment are also both tables)
I have no idea what I am doing (Maybe some days, but today I am feeling pretty confident I am not crazy)
A quick summary of queries I ran and the results that were outputted (I cant post a screenshot yet).
SELECT SCHEMA_NAME(); -- Default schema, returns "dbo"
select * from sys.databases; -- Returns 1 row of my organizations database
SELECT * from sys.schemas; -- Returns 1 row, name of "dbo", schema_id of 1, and principal_id of 1
select * from sys.tables t where t.name in ('attachment', 'fileattachment') and t.schema_id = 1;
select * from sys.views
-- returns two rows for the tables fileattachment and attachment
select object_id('dbo."attachment"') ;--returns null
select object_id('"attachment"'); --returns null
select object_id('attachment'); --returns null
select object_id('fileattachment'); --returns null
select object_id('sys.tables'); -- returns -386, so object_id does in fact execute within this database
select distinct type_Desc FROM sys.objects -- returns foreign_key_constraints, and user_table ... no views
SELECT CHECKSUM_AGG(CHECKSUM(*))
FROM attachment;
SELECT CHECKSUM_AGG(CHECKSUM(*))
FROM fileattachment;
--return the exact same result;

Best alternate of SQL Server rowversion (IROW_VERSION) in PostgreSQL? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a row version column in SQL Server table. At the time of update and insert command auto generate value automatically inserted/updated in this column. I need same in PostgreSQL. One option is to use function trigger with sequence generation but it may cause locking issue. What is the best practice/alternate in PostgreSQL.
The question is somewhat unclear. rowversion in SQL Server is only used as a concurrency token in optimistic concurrency scenarios. This is faster than a trigger that updates a LastModified timestamp or increments a stored column.
The equivalent in PostgreSQL is the system-provided xmin column:
xmin
The identity (transaction ID) of the inserting transaction for this row version. (A row version is an individual state of a row; each update of a row creates a new row version for the same logical row.)
Essentially, for a single row, xmin always changes after every modification, just like rowversion does. It's faster than a trigger too, since it requires no extra effort.
The NpgSQL provider for Entity Framework uses xmin as a concurrency token.
If you want to implement optimistic concurrency manually, read the xmin column in your SELECT statement and use that value in updates, eg:
SELECT xmin, ID, Name FROM sometable;
Which returns
xmin | ID | name
------+----+------
123 | 23 | Moo
And then
UPDATE sometable
SET name = 'Foo'
WHERE ID = 23 AND xmin = 123
If the row was modified by some other transaction, xmin won't match and no changes will be made. You can detect that by checking how many rows were changed using your provider's API. That's how rowversion works too.
Another possibility mentioned in the linked question is to use the RETURNING clause to return some value to the client. If no value is returned, the statement failed, eg:
UPDATE sometable
SET name = 'Foo'
WHERE ID = 23 AND xmin = 123
RETURNING 1
Not sure what "locking issue" you are talking about, but you can get something equivalent (assuming I understood the "row version" thing correctly) without a sequence:
create table some_table
(
.... columns of the table ...,
row_version bigint not null default 0
);
Then create a trigger function:
create function increment_row_version()
returns trigger
as
$$
begin
new.row_version := old.row_version + 1;
return new;
end;
$$
language plpgsql;
By using the old record, it's impossible to overwrite the row version value in an UPDATE statement.
And then create the trigger for every table where you need it:
create trigger update_row_version_trigger
before update on your_table_name_here
for each row
execute procedure increment_row_version();
If you also want to prevent inserting e.g. a higher number as the start number, you can extend the trigger to run on insert and update and in case of an insert assign the desired start value explicitly.
If you need a global value across all tables (rather than one number for each table as the above does), create a sequence and use nextval() inside the trigger rather than incrementing the value. And no, the use of a sequence will not cause "locking issues".
The trigger would then look like this:
create function increment_row_version()
returns trigger
as
$$
begin
new.row_version := nextval('global_row_version_sequence');
return new;
end;
$$
language plpgsql;
and can be used for both insert and update triggers.

How to check if a value in the column gets updated? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have column named HireDate in table named employeeInfo. I simply need to check whenever the value or Date in the HireDate column gets updated using simple SQL script.
I am unable to write a simple script by which I can check it.
You need to put trigger on the table. And if you want to execute your script when HireDate changed you can use "IF UPDATE(HireDate)". Check the following sample :
CREATE TRIGGER dbo.TR_employeeInfo_CheckHireDate
ON dbo.employeeInfo
AFTER UPDATE--,INSERT
AS BEGIN
SET NOCOUNT ON;
IF UPDATE (HireDate)
BEGIN
--put your Update,Delete or Insert statments here
END
END

Error with select case statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to convert this T-SQL query into Oracle?
if((select case
when (select top 1 AlertMessage
from ims.dbo.alertlist
where SystemID=#meter
order by TimePeriod desc
) like '%NO_COMMUNICATION_Resolved' then 1
else 0 end)=1)
begin
INSERT INTO [ims].[dbo].[alertlist]
([SiteID],[ThresholdNumber],[SystemID],
[AlertMessage],[TimePeriod],[AlertType],[PollID])
VALUES
(1,#thresnumber,#meter,#message,getdate(),1,0)
end
As pointed out by Dan Puzey, your question is too broad and it would require a lot of trial and error. However, I'll try to put you on the right track with something that might solve the first part of your problem.
DECLARE v_IsMessageResolved int;
-- This query will retrieve the value of the first row returned by the sub-query, mimicking the TOP 1 of SQL Server, and it will store the value of MessageResolved in a Variable
SELECT
MessageResolved into v_IsMessageResolved
FROM
(
-- This query will return 1 for all the Messages that match the LIKE clause, ordered by TimePeriod in descending order.
SELECT
CASE
WHEN AlertMessage LIKE '%NO_COMMUNICATION_Resolved' THEN 1
ELSE 0
END AS MessageResolved
,RANK() OVER (ORDER BY TimePeriod DESC) AS MessageRank
FROM
ims.alertlist
WHERE
(SystemID = :meter)
)
WHERE
(MessageRank = 1)
-- At this point, it will be a matter of checking the value of v_IsMessageResolved and, if it's "1", run the INSERT
Please note that I know SQL Server very well, but I never used Oracle, therefore my solution might not be perfect (or even run at all, as I don't have an environment to test it). This also means that you can find the answers to the remaining questions you might have with a simple search, as I did. :)

maintain history through trigger in asp.net [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Server history table - populate through SP or Trigger?
I am using this trigger
CREATE TRIGGER [dbo].[Band_Level_trg]
-- ALTER TRIGGER [dbo].[Test_PTA_Table_Update_trg]
ON [dbo].[Band_Level]
INSTEAD OF UPDATE
AS
SET NOCOUNT ON
DECLARE #key int
SET #key = (SELECT band_level_id FROM Inserted)
UPDATE Band_Level
SET band_level_name = band_level_name, description = description
WHERE band_level_id = #key
INSERT INTO dbo.Band_Level
(band_level_name, description)
(SELECT band_level_name,description
FROM Inserted)
but i want to show history on another page.it shows history on same page
Given this other question you posted:
maintain history through trigger in asp.net
(which sorry to say, is also horribly explained)
I think I figured out what you want to do. You want to keep a "history" of the changes using this trigger. Also, what I figured is that, you are "showing the history in the same page" because the trigger inserts on the same table you're updating!
The purpose of the history is to do it on ANOTHER table, if not, your history will become actual data of the table you wanna keep a history of.
You should create another table with the same columns and change the trigger accordingly. Just create a Band_Level_History table and change the trigger to save the changes there. That's it. Like this:
Instead of:
INSERT INTO dbo.Band_Level
Put:
INSERT INTO dbo.Band_Level_History
Also, I'd restructure the triggers in a different way. You should REALLY read this article:
https://web.archive.org/web/20210608144836/http://www.4guysfromrolla.com/webtech/091901-1.shtml
It's short so please read it. Also, next time please try to explain things a little better so everyone can understand. I'm aware that you probably have a language barrier but that's OK. Just try and do your best, I'm from Argentina and I can assure you: eventually you'll learn English if you are consistently trying.
Hope this helps

Resources