SQL Server trigger to auto-populate entire column - sql-server

If I have a table called AccuralMonth with two columns AccuralID and AccuralMonth.
and another table called Employee with a column called AccuralMonth too.
I want the function that when a number is entered into the AccuralMonth Column of the AccuralMonth table, it auto-populates all entries in the Employee table.
I have tried using a trigger but it did not work. I got an error when trying to insert value as it would of set a primary key value to null.
Create trigger MergeAccurual on [dbo].[AccuralMonth]
after insert,DELETE,UPDATE
as
begin
MERGE [dbo].[Employee] as E
USING [dbo].[AccuralMonth] AS am
ON E.[accrualmonth] = am.[AccuralMonth]
WHEN MATCHED THEN
UPDATE SET E.[accrualmonth] = am.[AccuralMonth]
WHEN NOT MATCHED BY TARGET THEN
INSERT([accrualmonth]) VALUES(am.[AccuralMonth]);
end
Any Ideas? Or even a better way to implement a way to set all values in AccuralMonth in Employees to a certain value as I do realize this is poor design.
I'm using these tables for a asp.net MVC web app

Related

Get trigger inserted row id's in stored procedure

I have a stored procedure which updates multiple rows in a column as mentioned below:
update tableA
set isactive = 0
where email = ''
TableA has update trigger to insert into tableALog if isactive is changed.
Now in my stored procedure after update statement is executed I need to get tableALog primary key values.
I have used following ways bu no luck.
##identity - failed because it returns last updated value. But I need list of primary key values inserted in log table
OUTPUT inserted. - cannot use this because it always works on current scope in stored procedure. But I need table values which are inserted from trigger.
Please let me know if you have any suggestions.
This started as a comment but it's getting too long, so...
Sharing data between stored procedures and the triggers they activate is tricky,
Since triggers can't take parameters not can they return values.
From my experience, The best way to achieve such a thing involve adding a column to the table the trigger is set on to identify the records the trigger is working on, and adding a table (could be a temporary table) for the trigger to output the data and the stored procedure to read from.

Relations between Table and View using Microsoft SQL

Is there a natural option to establish a relationship between table and view or i should use trigger as a workaround to check that the data consistency?
I have a lookup view (for some reason i need it to be view and not a table).
I want to insert records to a different table. one of the values of the record i want to insert MUST be one of the ids from the lookup view.
For example:
ViewCities (CityId, CityName) -- This is the lookup View. the table behind the view located on a different database.
now i want to insert new row to tblUsers. one of the row columns is CityId. I want that not one will be able to insert a row to tblUsers that includes cityid that not exists on ViewCities.
You have two options that I am aware of to maintain referential integrity. You cannot use a foreign key constraint because you said that the tables are in two separate databases. The options are:
1. Use triggers, as you had mentioned.
2. Use a check constraint which references a user defined function which does the check.
For example:
Let's say I have a database named test, and another database is the Northwind database. In my test database I want to create a table which records names of users. The check I want to enforce is that the user name must be one of the LastName's of a user in the Northwind database. I first create a UDF like so:
create function chk_name (#name varchar(50))
returns bit
as
begin
declare #name_found bit=0
if exists(select * from Northwind..Employees where LastName=#name)
begin
set #name_found=1
end
return #name_found
end
Then, I create the table with a check constraint like so:
create table tst
(name varchar(50) check ( dbo.chk_name(name)=1 )
)
Now, if you try to insert a row into the tst table, it must be one of the Last Names of the Employees table in the Northwind database.

Stored procedure to generate a unique id column

Good day
I have a situation where two users are saving data to the same database and there are primary key conflicts.
Is it possible to write a stored procedure or trigger which will generate a unique identity by adding two columns.
For instance: I have table2 related to table1 by Table1ID. Increment and seed is 1 for both.
If I had to add a row to table2 I would like the autogenerated ID number to be added to a text column thereby making it unique. So the ID would be something like JoeSoap5.
If you want to generated something unique you can use the build-in function "NEWID()". Type and executed the following code:
SELECT NEWID()
If you need to insert record in second table when record in your first table is inserted, is is possible to implement this using TRIGGERS. In your case you can use "AFTER INSERT TRIGGER" or "BEFORE INSERT TRIGGER" - generally this will be a piece of code that will be executed AFTER/BEFORE row in your first table is inserted.
You don't specify your SQL Server version.
SQL 2012 introduces the concept of a sequence - http://msdn.microsoft.com/en-us/library/ff878091.aspx - which would allow you to do just what you want.

SQL server trigger question

I am by no means a sql programmer and I am trying to accomplish something that I am pretty sure has been done a million times before.
I am trying to auto generate a customer number in sql every time a new customer is inserted, but the trigger (or sp?) will only work if at least the first name, last name and another value called case number is entered. If any of these fields are missing, the system generates an error. If the criteria is met, the system generates and assigns a unique id to that customer that begins with letters GL- and then uses 5 digit number so a customer John Doe would be GL-00001 and Jane Doe would be GL-00002.
I am sorry if I am asking too much but I am basically a select insert update guy and nothing more so thanks in advance for any help.
If I were in this situation, I would:
--Alter the table(s) so that first name, last name and case number are required (NOT NULL) columns. Handle your checks for required fields on the application side before submitting the record to the database.
--If it doesn't already exist, add an identity column to the customer table.
--Add a persisted computed column to the customer table that will format the identity column into the desired GL-00000 format.
/* Demo computed column for customer number */
create table #test (
id int identity,
customer_number as 'GL-' + left('00000', 5-len(cast(id as varchar(5)))) + cast(id as varchar(5)) persisted,
name char(20)
)
insert into #test (name) values ('Joe')
insert into #test (name) values ('BobbyS')
select * from #test
drop table #test
This should satisfy your requirements without the need to introduce the overhead of a trigger.
So what do you want to do? generate a customer number even when these fields arn't populated?
Have you looked at the SQL for the trigger? You can do this in SSMS (SQL Server Managment Studio) by going to the table in question in the Object Explorer, expanding the table and then expanding triggers.
If you open up the trigger you'll see what it does to generate the customer number. If you are unsure on how this code works, then post the code for the trigger up.
If you are making changes to an existing system i'd advise you to find out any implications that changing the way data is inputted works.
For example, others parts of the application may depend on all of the initial values being populated, so after changing the trigger to allow incomplete data to be added, you may inturn break something else.
You have probably a unique constraint and/or NOT NULL constraints set on the table.
Remove/Disable these (for example with the SQL-Server Management Console in Design Mode) and then try again to insert the data. Keep in mind, that you will probably not be able to enable the constraints after your insert, since you are violating conditions after the insert. Only disable or reomve the constraints, if you are absolutely sure that they are unecessary.
Here's example syntax (you need to know the constraint names):
--disable
ALTER TABLE customer NOCHECK CONSTRAINT your_constraint_name
--enable
ALTER TABLE customer CHECK CONSTRAINT your_constraint_name
Caution: If I were you, I'd rather try to insert dummy values for the not null columns like this:
insert into customers select afield , 1 as dummyvalue, 2 as dummyvalue from your datasource
A very easy way to do this would be to create a table of this sort of structure:
CustomerID of type in that is a primary key and set it as identity
CustomerIDPrfix of type varchar(3) which stores GL- as a default value.
Then add your other fields and set them to NOT NULL.
If that way is not acceptable and you do need to write a trigger check out these two articles:
http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx
http://www.kodyaz.com/articles/sql-trigger-example-in-sql-server-2008.aspx
Basiclly it is all about getting the logic right to check if the fields are blank. Experiment with a test database on your local machine. This will help you get it right.

Compute hash-value of entered value when insert or update using sql server 2008 by triggers

I have a table with two columns {FlatContent, HashedContent}. Now I want to automatically compute the hash value of FlatContent when new row was inserted or an existing row was updated. To date, I've never used from trigger, so I can't do this by trigger or another approach which is exist to solve this issue.
Thanks if anybody can help me ;)
Instead of using a trigger, make HashedContent a persisted computed column in your table definition.
ALTER TABLE YourTable
ADD HashedContent AS HashBytes('SHA1', FlatContent) PERSISTED

Resources