How To Write Trigger To Enforce Constraint

Oct 12, 2014

how to i write a trigger to enforce this constraint..A rental can be made only if the customer is registered with the company and the car is not currently rented out. If not, the rental will not be successful.

View 1 Replies


ADVERTISEMENT

How Do I Write This Check Constraint?

Oct 25, 2007



Hi all,
Any advice much appreciated.

I have a table that defines the metadata of some values that will be stored in some generic table somewhere. Here's the table definition:


CREATE TABLE [dbo].[AttributeType]

(

[AttributeTypeID] [int] NOT NULL

, [AttributeTypeName] [nvarchar] (40) NOT NULL

, [AttributeDataType] [nvarchar] (40) NOT NULL CONSTRAINT CK_AttributeDataType_Values CHECK ([AttributeDataType] IN ('NVARCHAR','INT','DECIMAL','DATETIME'))

, [AttributeLength] tinyint NULL

, [AttributePrecision]tinyint NULL

, [AttributeScale] tinyint NULL

, CONSTRAINT CK_AttributeScale_Values CHECK (AttributeScale <= AttributePrecision)

) ON [PRIMARY]



What I want to do is write a constraint (or 4 constraints) that says:
If AttributeDataType = 'nvarchar', AttributeLength cannot be NULL, AttributePrecision must be NULL, AttributeScale must be NULL
If AttributeDataType = 'int', AttributeLength must be NULL, AttributePrecision must be NULL, AttributeScale must be NULL
If AttributeDataType = 'datetime', AttributeLength must be NULL, AttributePrecision must be NULL, AttributeScale must be NULL
If AttributeDataType = 'decimal', AttributeLength must be NULL, AttributePrecision cannot be NULL, AttributeScale cannot be NULL


Is that even possible? I've tried and failed (admittedly not for too long) to fathom a way of doing it.

-Jamie

View 7 Replies View Related

Read And Write A Constraint Or Default Value

Nov 20, 2007

Okay, maybe I'm getting ahead of myself.
Using SQL Server Express, VWD and .net 2.0 I've figured out how to drop a Table Column Constraint or Default Value/Binding and then Create it again using a stored procedure. What I can't figure out is how to retrieve that column's constraint value and write it to, say a label, in an aspx page, simply for reference. Is it possible? In this case the Data Type of the column is money.
I'm using it to perform a calculation to a column with a value that the user inserts into another column. (Column1(user input) minus Column2(with Default Value) = Column3(Difference). I just want to read Column2's Default Value for reference so I know whether to change it or not.

View 6 Replies View Related

Trigger + CONSTRAINT ???

Feb 9, 2004

I have 2 tables

Primary_Table (Key, ........)

Foreign_Table (Key_1, Key_2, ............)

I want this:

If I update the Key in Primary_Table then
Key_1 is Update where Key_1 = Key

AND

If I update the Key in Primary_Table then
Key_2 is Update where Key_2 = Key

I can not use CONSTRAINT because I can not use ON UPDATE CASCADE for this case (It not possible to use 2 CONSTRAINT WITH ON UPDATE CASCADE).

I WANT TO USE TRIGGERS

This is my trigger (but I am not sure it is the best way ?)

CREATE TRIGGER Test ON [Primary_table]
FOR UPDATE
AS

Declare @NewValue varchar(30)
Declare @OldValue varchar(30)

SET @NewValue = (Select Key From Inserted)
SET @OldValue = (Select Key From Deleted)

UPDATE [Foreign_Table]
SET [Foreign_Table].[Key_1] = @NewValue
FROM [Foreign_Table] WHERE [Key_1] = @OldValue

UPDATE [Foreign_Table]
SET [Foreign_Table].[Key_2] = @NewValue
FROM [Foreign_Table] WHERE [Key_2] = @OldValue


Sorry for my english.
Please consider I am a beginner

View 1 Replies View Related

Constraint Vs Trigger?

Aug 8, 2007

Hello,

I have a table that allows a user (from another table) to belong to multiple organizations. Part of this table's schema is a column that will be used to allow the user to indicate which organization that they belong to will be the primary one. A user can only have one PRIMARY organization. I was going to handle via an Insert or Update Trigger...checking to see if the userid already a Primary. However, now I am wondering if a Constraint would be the way to go? I admit though, I don't know enough about Constraints to know how this would work.

The table's schema is like:
UserOrg
UserOrgID (an identity column)
UserID (foreign key to the user's table)
Org (the name of the org)
PrimaryOrg (bit column)

Thanks for any help.
- Will.

View 3 Replies View Related

Constraint In Trigger

May 3, 2007

I do not know this is the correct way to do this, but somehow thisisnt working. All I want is not to have a null value in field A ifthere is a value in field Bheres the codeCREATE TRIGGER tiu_name ON tblNameFOR INSERT, UPDATEASDECLARE @FieldA AS REAL, @FieldB AS REAL;SELECT @FieldA=FieldA, @FieldB=FieldBFROM Inserted;IF (@FieldB IS NOT NULL) AND (@FieldA IS NULL)RAISERROR('Error Message',1,2);GOPlease Help.

View 1 Replies View Related

Constraint Or Trigger

May 12, 2007

Hi Guys,



I am not sure if this is the correct forum but i thought i'd ask and see if you can help me!



I have a table with 2 columns:



1st column will house numbers from 1 to 50

2nd column will be date



I want the users to be able to pick a number for certain date and enter it to the table, however I don't want the system to allow the same number for the same date. I was looking at constraints and triggers but can't make out what exactly i should use and how. The Insert will be initiated from ASP page on our intranet. Please help!!!



Regards

SD









View 1 Replies View Related

Constraint Trigger

May 1, 2008

Hello all

The majority of my database experience comes from ORACLE and i am trying to use some functionality that i have already used in Oracle into a project i am working on in MSDE.

I want to create a trigger that uses a DML constraint that will prevent a tenants from being inserted into a house if the bedroom count is less or equal to the number of tenants currently in the house.

The oracle code is below


CREATE OR REPLACE TRIGGER Tenant_room_check
BEFORE INSERT or update of tenant_ID ON Tenant
FOR each row
as (new.tenant_ID is not null)
DECLARE
Tenant_count NUMBER;
Bedroom_count NUMBER;
BEGIN

select count(Tenant_ID) as Tenant_count
from Tenant
where tenant_ID = :new.tenant_ID
and House_ID = 1
AND Tenant_status = 1;

select count(ROOM_ID) as bedroom_count
from Room
where Room_Name = 'Bedroom'
and House_ID = 1

if (Tenant_count > Bedroom_count)
then raise_application_error(-20601,
'you cannot have more tenants than the number of bedrooms in a student house');

END IF;
END;
/

Ideally I would like to pass the HOUSE_ID and the TENANT_ID from my application using @variablename

I have been looking over forums and in books but i am getting all confused over the syntax to use.

Please Help
Many Thanks
Quish

View 5 Replies View Related

Constraint/trigger In Sql Server In Asp.net

Nov 24, 2006

In my Projecti want to check the date at the time of insert in A-Tablethat it should be Greater than (>)  Date Defined in B-TableNote:-B-table have only one record  so plz tell me how can i do using Sql-Server Backend only 

View 3 Replies View Related

Referential Constraint Vs Trigger

Jan 18, 2007

I am using SQL server 2000. I have a parent table 'MimeTypes' with primary key 'mimetype'. This is referenced as foreign key in table 'AssetTypes' as column 'BaseMimeType'.
The referential constraint is simple :
alter table AssetTypes
add constraint FK_ASSETTYPES_REF_BASEMIMETYPE foreign key (BaseMimeType)
references MimeTypes (MimeType) on update no action on delete no action;

I have FOR Update trigger on parent table ('MimeTypes') which is as follows:

CREATE TRIGGER trg_MimeTypes_update ON MimeTypes FOR UPDATE
AS
IF UPDATE(MimeType)
BEGIN
UPDATE AssetTypes
SET BaseMimeType = (select MimeType from inserted)
FROM AssetTypes as A
JOIN deleted as d on A.BaseMimeType = d.MimeType
END;

********
The problem is simple. I want to execute a update query on parent table ('MimeTypes') which modifies 'mimetype' value referenced by child. I dont want to include cascade option in constraint.
When such query is executed error comes as : UPDATE statement conflicted with COLUMN REFERENCE constraint 'FK_ASSETTYPES_REF_BASEMIMETYPE'. The conflict occurred in database 'default.db', table 'AssetTypes', column 'BaseMimeType'.
*****
Is there any way to do this?

View 5 Replies View Related

Getting A Constraint Value From Query In A Trigger?

Mar 1, 2005

say i have a query like:

UPDATE table SET status = 1 WHERE id = 1000

if i have a trigger on that table, is there anyway i can get the id ?

i know i can get the status by SELECT status FROM Inserted, but anyway to get what the id is? or would i just have to update the id as well?

thanks

View 4 Replies View Related

Check Constraint Within A Trigger

Aug 7, 2014

I want to incorporate a Check constraint within a trigger, based on this but im struggling with the coding.Assuming that is an Alphanumeric field you should be checking what value is in the alphanumeric column from inserted, comparing it with whatever is in the AMGR_User_Fields_Tbl to see if there’s a duplicate and then raising the error...This is my Trigger:

ALTER TRIGGER [dbo].[DUPLICATES]
ON [dbo].[AMGR_User_Fields_Tbl]

FOR INSERT, UPDATE
AS
DECLARE @Alphanumericcol VARCHAR (750)

-- This trigger has been created to check that duplicate rows are not inserted into table.

-- Check if row exists
SELECT @Alphanumericcol
FROM Inserted i, AMGR_User_Fields_Tbl t

[code]....

View 1 Replies View Related

Trigger Vs Uniqueness Constraint Order

Jul 5, 2000

Hi,
Can anyone tell me the order in which uniqueness constraints on indexes are enforced vs. when triggers are executed ? I have a unique constraint on an index and a trigger on the column on which the same index has been created. When a row is inserted, the trigger checks if the value for that column already exists in the table - if not, it inserts the row as is, else it gets the max() val of the column (based on another key column) and increments it by one, then does the insert. Creating an index across the two works fine, but if I set the Unique Values property for the index, subsequent inserts bomb out - yet there aren't any duplicates in the final table, as the trigger ensures this. Anyone got any ideas on this? My deduction is that the uniqueness constraint gets enforced before the trigger gets executed, but at the same time this *seems* illogical, as the row has not been inserted into the table at the point where the trigger is executed.

Regards,
Jon Reade.

View 2 Replies View Related

Trigger? Constraint? Computed Column?

Feb 23, 2007

Hi.

I was wondering how I should go about doing this thing. I need to put a value in a column that is based on values on other columns in the same row.

When this statement executes I need to put a value in Col3.

insert into myTable(Col1, Col2)
values(25, -14)

Something like so:

if(Col1 >0 AND Col2 <0)
set Col3 = Col1 - Col2
else
set Col3 = Col1;

I don't now quite how to solve this. I am really going to need this value in a column. Calculating the value at retrieval is not on option...

I appreciate all help. I'm using SQL Server 2005.

Thanks!

View 2 Replies View Related

How To Write This Trigger

Nov 1, 2006

I have table T1 with the fields: ID,Type,Status,F1,F2,F3,F4 in database1. I also have T2 in Database2 which has the same fields and some extra fields. Now based on the T1.Type=Insert or Update, I need to perform either update or Insert in T2 based on where T1.ID=T2.ID and T1.Status<>’Done’. If this is a success, I need to set T1.Status=’Done’ for the updated records. So this should only be updated records. T1 is a frequently inserted table, so there might be more than one record coming there at the same time. How should I write my insert trigger and correctly set T1.Status=’Done’, any example would be greatly appreciated.

View 9 Replies View Related

How To Write A Trigger

Dec 20, 2005

I have a table with a last_updated field and a review_date field.  I would like to write a trigger that when the last_updated field is updated, it adds 6 months to the review_date field.
This is what I started, not sure of how to finish it:
CREATE TRIGGER Update_Review_Date
ON dbo.Category_Type
FOR Update
AS
 
 

View 6 Replies View Related

Where Do We Write A Trigger

Feb 22, 2005

Hi,
I am pretty new to MSSQL server environment. In Oracle i write Trigger and compile it at command prompt in case of SQL plus the same way i need to know where we write the script for SQL server. Is there any menu driven editor where we can write or simply writing a trigger in SQL Query analyzer and executing it will work

Please advice.

Thanks and Regards
D. Pavan Kumar

View 4 Replies View Related

How To Write Trigger

Mar 28, 2007

hi

I want to audit data before update or delete with modified date,userid,machineid

How to write trigger for it

Example
-------

I have a table as Immigration With Following fields

Employee_id int(foriegn key)
Passport no varchar(50)
Issue date datetime
Expiry date datetime

Iwant to store data or audit data before update or delete data from above table



Malathi Rao

View 1 Replies View Related

INSTEAD OF TRIGGER CAN WE WRITE SP

Apr 29, 2008

Great.

Can you give it a first try? Post it and we will fix it.

View 3 Replies View Related

Write A Trigger

Nov 20, 2006

Hi all,

i want to write a trigger which returns a row to the application whenever a row is inserted into a table.

E.g.

When row R1 is inserted into a table T1.

the trigger should return the R1 to the application.

Wanna be coding monkey...

View 7 Replies View Related

How To Write This Trigger

Nov 1, 2006

I have table T1 with the fields: ID,Type,Status,F1,F2,F3,F4 in database1. I also have T2 in Database2 which has the same fields and some extra fields.

Now based on the T1.Type=Insert or Update, I need to perform either update or Insert in T2 based on where T1.ID=T2.ID and T1.Status<>€™Done€™. If this is a success, I need to set T1.Status=€™Done€™ for the updated records. So this should only be updated records.

T1 is a frequently inserted table, so there might be more than one record coming there at the same time. How should I write my insert trigger and correctly set T1.Status=€™Done€™, any example would be greatly appreciated.

View 6 Replies View Related

How To Write A Trigger For Update

May 28, 2007

Hello All,
 As we have INSERTED,DELETED tables to trace what values are inserted and deleted, how to write triggers for Updates on the tables.
Your help would be appreciated.
Shiva Kumar

View 3 Replies View Related

How To Write Trigger For ON_DELETE_CASCADE?

Jul 23, 2005

Hello ExpertsI am new in Sql triggers and i would like some helpI have a Table called ITEM and another callded SOURCE[ITEM]ItemNo,ItemName,SourceNo[Source]SourceNo,Sourcei want to create a Trigger so when i delete a record from [SOURCE] allthe records in [ITEM] where item.SourceNo = [SourceNo that I deletedfrom SOURCE]How can i do that?

View 1 Replies View Related

CLR Trigger To Write File.......

Feb 28, 2006

Hello, theres,

I have a request to write to a file whenever new record added to the table.

When records insert row by row, it goes well. but when more than 2 session insert at the same time, sometimes it duplicate some record in the file. I try to add synchonize code ( like lock , Monitor) but it doesn't work. any idea ?

Regards,

Agi

View 3 Replies View Related

Converting Multi-column Referential Constraint Into A Trigger

Feb 28, 2008

Hi there,

I am looking for a way to define a trigger that is a replacement for a multi-column foreign key.

I know how to a convert a single-column foreign key constraint into a trigger (i.e., to resolve diamond-structured references).

CREATE TABLE parent_tab
(
col_a INTEGER NOT NULL,
CONSTRAINT pk PRIMARY KEY(col_a)
);

CREATE TABLE child_tab
(
col_x INTEGER NOT NULL,
CONSTRAINT fk FOREIGN KEY (col_x) REFERENCES parent_tab(col_a) ON DELETE CASCADE
);

The conversion would remove the foreign key definition and add this trigger:

CREATE TRIGGER tr_single
ON parent_tab INSTEAD OF DELETE
AS BEGIN
DELETE FROM child_tab WHERE (child_tab.col_x IN (SELECT col_a FROM deleted))
DELETE FROM parent_tab WHERE (parent_tab.col_a IN (SELECT col_a FROM deleted))
END;

Unfortunately, now I need to resolve a situation where there is involved a multi-column foreign key.

CREATE TABLE parent_tab
(
col_a INTEGER NOT NULL,
col_b INTEGER NOT NULL,
CONSTRAINT pk PRIMARY KEY(col_a, col_b)
);

CREATE TABLE child_tab
(
col_x INTEGER NOT NULL,
col_y INTEGER NOT NULL,
CONSTRAINT fk FOREIGN KEY (col_x, col_y) REFERENCES parent_tab(col_a, col_b) ON DELETE CASCADE
);

This does not work, because the temporary table "deleted" might contain more than one row. How do I make sure that the values belong to the same row?

-- incorrect trigger, might delete too many rows
CREATE TRIGGER tr_single
ON parent_tab INSTEAD OF DELETE
AS BEGIN
DELETE FROM child_tab WHERE (child_tab.col_x IN (SELECT col_a FROM deleted) AND child_tab.col_y IN (SELECT col_b FROM deleted))
DELETE FROM parent_tab WHERE (parent_tab.col_a IN (SELECT col_a FROM deleted) AND parent_tab.col_b IN (SELECT col_b FROM deleted))
END;

-- some magic needed :-)
CREATE TRIGGER tr_single
ON parent_tab INSTEAD OF DELETE
AS BEGIN
DELETE FROM child_tab WHERE (child_tab.col_x IN (SELECT col_a FROM deleted AS t1) AND child_tab.col_y IN (SELECT col_b FROM deleted AS t2) AND row_id(t1) = row_id(t2))
DELETE FROM parent_tab WHERE (parent_tab.col_a IN (SELECT col_a FROM deleted AS t1) AND parent_tab.col_b IN (SELECT col_b FROM deleted AS t2) AND row_id(t1) = row_id(t2))
END;

I know the trigger definition above is ***... but I hope that it helps to make clear what I need.

Btw., I use SQL Server 2005.

Thanks in advance,

slowjoe

View 3 Replies View Related

How To Write Trigger Based On Certain Condition

Nov 8, 2005

One of my table called as 'customertable' contains following fields

customername, emailid, subscriptionendperiod

Example records are:

david, david@john.com, 12/20/2005(mm/dd/yyyy format).

My question is that: Just one month before subscriptionendperiod that is on 11/20/2005(mm/dd/yyyy) an automatic email should go to david@john.com with the message 'Your subscription period ends on 12/20/2005'

How to write trigger for this.

Please Note : No ASP code is invloved in this.
Only MSSQL coding to be done.


Regards

View 3 Replies View Related

Trigger To Encrypt Field Before Write

Apr 28, 2006

Hello,While working through my encryption questions from preivous posts, I amfinding that I may have to resort to use triggers to do the encryption(not that this is the only way, but might be the best way for mycircumstances).I would like to create a trigger that will encrypt the field before thewrite is committed.I've found serveral posts about triggers, but nothing that fits what Iwish to do.Upon an insert or update I want to modify the ssn field with this:cast(EncryptByAsymKey(AsymKey_ID('Student_aKey'), cast(SSN asnvarchar(11))) as nvarchar(40))so, ssn '123456789' in SSN would become <something encrypted> in SSNThis is the trigger I have so far, but it is generating an error:CREATE TRIGGER F_Student_SSN.eSSNON F_STUDENT_SSNINSERT, UPDATEAS SELECT cast(EncryptByAsymKey(AsymKey_ID('Student_aKey'), cast(SSN asnvarchar(11))) as nvarchar(40))TIARob

View 3 Replies View Related

Can Write More Than One Trigger For A Single Table(sql Server 2000)?

Jan 17, 2008

Hi
 
    Can u please send the answers for this
 
  1 . Can write more than one trigger for a single table(sql server 2000)?
 
  2. how to create the editable gridview? While clicking particular cell it should be  changed to
       Edit mode , and I want option for creating new row and delete option, search option
 

View 1 Replies View Related

Column Level Constraints... I Need A Constraint, Not A Rule, Or A Trigger Or A Stored Proc... Thnx.

Jul 17, 2001

Hello all.

First of all, I've been a reader of swynk.com for quite sometime now, and I'd like to say 'thank you' to everyone who contributes.

Today, I'm the town moron.. haha I'm having issues with column level constraints. I have a varchar(50) where I want to keep *,=,#,/, .. etc, OUT OF the value input. I don't want to strip them. I simply want for sql to throw an error if the insert contains those (and other characters). The only characters that I want in the column are A-Z and 0-9. However, it's not a set number of characters per insert. It always varies... There has to be an easier way to do this than creating a constraint for every possibilty... Any help would be greatly appreciated.

tia,

Jeremy

View 1 Replies View Related

T-SQL (SS2K8) :: Trigger To Call A Program To Write Text File Onto A Folder In Server

Apr 29, 2014

I have created a trigger to call a program that is written by our program. The program is basically read the record in the table and write to a text file, then delete the record from the table.

The trigger is a after insert trigger. After we added the trigger, we insert a record to the table. The result is that the record still and did not get deleted. Also, the text file didn't get created either. It seems that it take a long time for the record to be written to the table.

But if we just run the program (a exe file), it can write a text file in the folder and delete the record. the trigger is basically:

USE [Zinter]
GO
/****** Object: Trigger [dbo].[ZinterProcess] Script Date: 04/29/2014 18:34:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

[Code] ....

View 9 Replies View Related

How To Enforce Password Complexity

Apr 13, 2004

Hi,
We testing our security.
For NT logins user password complexity and expiration enforced by NT


1.Any way to enforce password complexity and expiration for standard sql login ?

2.any way to check if existing sql login passwords less then N number of characters?

Thank you
Alex

View 3 Replies View Related

Enforce Foreign Key Constraints

Oct 22, 2007



I have recently restored an SQL Server 2000 database on SQL Server 2005
A number of constraints on the database had previously been disabled

A monthly process that is carried out, imports data into 'Table A'.
This process now crashed, being unable to truncate table as it referenced by 'Table B'

Although when i check the properties of the constraint the 'enforce foreign key constraints' is set to no.

Is there a known issue with restoring databases on 2005,

Any help greatly appreciated.

Micheal

View 2 Replies View Related

SQL Login Enforce Password Policy

Mar 20, 2007

I have a 3 node cluster running windows 2003 x64 sp1 and SQL Server 2005 version 9.00.2153. My problem is the following...

This Saturday I migrated a web application's database to this server. After restoring the database I created the sql login for the service account, set the password and disabled the password policy for this login. I then ran sp_change_users_login to attach the already existing db user with the same name to the login. I changed the connection string for the application, tested the application connectivity and functionality then detatched the old database on the old server. Everything went like clockwork, no problems at all.

Come Monday morning at 8:35 I started getting alerts that the web site was down. I tested the site and sure enough it was down. I then attempted to connect to the database server using the login that was created for the app and the connection failed. I logged in with my ID and got in fine. Nothing showing to be wrong with the DB, I checked the new login and somehow the "Enable Password Policy" had been set for the new login. I disabled it and still no connection. I went to the database and checked the DB user and somehow the link between it and the login no longer existed. I reran the sp_change_users_login and restested the web site and verified that that web site was back online.

My question is this, is there any stored proc that resets these values back to default for some reason, a series of events that might revert the "Enable Password Policiy" to the default for a login, or is there a particular domain level operation that might occur such as Security Polcies that would affect these settings in SQL?

No one else was on the machine when I went to check it out at 8:40 so it has left me puzzled.

Any help would be appreciated.

Thanks.

Zach

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved