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.
I have a question about a table with triggers or maybe a check constraint.I have the following create tables:
create table bid( seller char(10) not null, item_nummer numeric(3) not null, )
create table Item( startprice char(5) not null, description char(22) not null, start_date char(10) not null, end_date char(10) not null, seller char(10) not null, item_nummer numeric(3) not null, )
What i'm trying to make is this trigger/constraint: colomn "seller" from table Item will get NULL as long as systemdate is > start_date and end_date, then it will get the value from seller from table bid on the same item_nummer in both table).
I am trying to create table with following SQL script:
Code Snippet
create table Projects( ID smallint identity (0, 1) constraint PK_Projects primary key, Name nvarchar (255) constraint NN_Prj_Name not null, Creator nvarchar (255), CreateDate datetime );
When I execute this script I get following error message:
Error source: SQL Server Compact ADO.NET Data Provider Error message: Named Constraint is not supported for this type of constraint. [ Constraint Name = NN_Prj_Name ]
I looked in the SQL Server Books Online and saw following:
CREATE TABLE (SQL Server Compact) ... < column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL | NOT NULL ] | [ PRIMARY KEY | UNIQUE ] | REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ]
As I understand according to documentation named constraints should be supported, however error message says opposite. I can rephrase SQL script by removing named constraint.
Code Snippet
create table Projects( ID smallint identity (0, 1) constraint PK_Projects primary key, Name nvarchar (255) not null, Creator nvarchar (255), CreateDate datetime ); This script executes correctly, however I want named constraints and this does not satisfy me.
This isn€™t an problem as such, it€™s more of a debate.
If a table needs a number of update triggers which do differing tasks, should these triggers be separated out or encapsulated into one all encompassing trigger. Speaking in terms of performance, it doesn€™t make much of an improvement doing either depending upon the tasks performed. I was wondering in terms of maintenance and best practice etc. My view is that if the triggers do totally differing tasks they should be a trigger each on their own.
We are using SQL CE 3.5 on tablet PCs, that synchs with our host SQL 2005 Server using Microsoft Synchronization Services. On the tablets, when inserting a record, we get the following error: A duplicate value cannot be inserted into a unique index. [ Table name = refRegTitle,Constraint name = PK_refRegTitle But the only PK on this table is RegTitleID.
The table structure is: [RegTitleID] [int] IDENTITY(1,1) NOT NULL, [RegTitleNumber] [int] NOT NULL, [RegTitleDescription] [varchar](200) NOT NULL, [FacilityTypeID] [int] NOT NULL, [Active] [bit] NOT NULL,
The problem occurs when a Title Number is inserted and a record with that number already exists. There is no unique constraint on Title Number. Has anyone else experienced this?
Hi, I am trying to figure out how to do this. For each row, only one out of two columns(id1,id2) should be populated. So if the id1 column is already populated and the application tries to fill in something for id2 then we just simply don't want to allow that and vice versa.
I am thinking triggers is the way to go. What do you think? thanks Rozina
using alter table syntax how can i insert the field TramingChoiceCd Extend the constraint on NetwkChannel table UQ__TetwkChannel__50FB042B to include TramingChoiceCd
Which is the preferred method Rule, Check Constraint or Trigger? I want to set a column to todays date when the column is = "T" else when "F" set it to a future date. Each time there is a insertion into the table.
I have a varchar field in a table.I want to restrict the entries in that field as "yes" or "no" nothing else.No record will be allowed for this field without yes or no.My question is is it possible without using any trigger for the table?I want to do it with the help of a constraint.
When I see desing table option in enterprise manager of a table I don't see any constraints, but when I extract ddl I can see all 6 of them. They are all unique constraints not the check constraints. Is this normal. I am new to SQL Server and would appreciate some explanation.
Hi I was wodering how to add an OR statment right in the Check Constraint expression. This is what I am starting with in the database ([zip] like '[0-9][0-9][0-9][0-9][0-9]') and what I want well not exact but this would answer my question ([zip] like '[0-9][0-9][0-9][0-9][0-9] || [A-Z][A-Z][A-Z][A-Z][A-Z]') Thanks for any help
how can i implement delete constraint? i mean i don't want the rows of the primary key table to be deleted if they are used as foreign key in some other table. so i want to check if that PK is used as foreign key in other tables before deleting.
student --- enrollment is 1- to - many . ssn is pk in student. ssn and courseid is pk in enrollment. later I added the foreign key constraint FK_SSN in enrollment table reference student table. it is ok. enrollment --- lessonhistory is 1-to -many, ssn, courseid and lessonid is pk in lessonhistory . I tried to set FK_SSN foreign key constraint in lessonhistory table reference enrollment table, it always show error message " no primary key in referewnce talbe enrollment " I don't know how to fix it. could you help me out, thanks!!
Can somebody tell me about on delete constraint and where should it be used - table having foriegn key?
coz want i want is- the moment i delete the data from the table whose primary key is been referenced as foreign key , The Data in all the tables where its primary key is beeen used as forein key should be deleted.
My company does medical billing for several clients. Each client may have a contract with several insurance companies (Payors) for rates for different procedures. I have a table named FeeSchedule with four (relevant) columns: Client, CPTCode (procedure code), Payor, and Fee.
Some Payors don't really negotiate, and have the same FeeSchedule for all clients. I know the right way to track that is have a separate set of records for each client, even for payors like medicare where every client will have the same set of records. However, the data-entry burden for populating that table would be very large, and I would like to use be able to have use a NULL client like a wildcard.
The problem is I then can't use client as part of the key, and I need to be able to restrict it so that if I have a NULL client for a specific CPT and Payor and I can't also have a another Client for that CPT and Payor.
Any ideas how to accomplish this or the equivalent functionality?
Countryid CountyNAme INIndia MYMalaysia UKUnitedKingdom here Countryid is the primary key.
2) MainDept
DeptID Deptname Countryid CMCashManagementIN CBConsumerBankingMY CSCustomer SupportIN IBInternetBankIN here deptid is the primary key
3) UserMaster
Uid Uname Deptid Countryid 001 Chris CMIN 002 Raja CSIN 003 Ram CBMY here Uid is the primary key.
The problem is when i change the countryid from one country to another for a deptname. THe change is not reflected in the usermaster table as it still shows the previous countryid. For eg. user Chris belongs to dept Cash management which is situated in india. Now if i change in mainDept table the cash management from india(IN) to say malaysia(MY).the corresponding change is not reflected in usermaster table.it still shows india. So when i query for chris in usermaster i get an error as i am searching in india for cash mangement. i tried using on update cascade but here it did not work as i have to make DeptID & countryID in MainDept table as composite key & use Deptid & countryid in usermaster as refernce key. Since i have 20-25 tables also referencing the above 2 tables i have to set reference key in all these tables & these tables are in turn referenced elsewhere in other tables. Thus i end up creating a large no. of composite keys. IS there any other way to solve this problem? note : In sqlserver we can give on update cascade still it has the above problem but in Oracle on update cascade is not possible
Can anybody suggest a solution for this in both sql server and in oracle
I am having problem to find the right syntax to DROP a column with contrainst and recrate it I get an error
if exists ( select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='myTable' and COLUMN_NAME='myDate' ) ALTER TABLE [dbo].[myTable] DROP COLUMN myDate GO
ALTER TABLE [dbo].[myTable] WITH NOCHECK ADD myDate datetime CONSTRAINT [DF_myDate] DEFAULT (GetDate()) GO
Query Analyser says : Server: Msg 5074, Level 16, State 1, Line 5 The object 'DF_myDate' is dependent on column 'myDate'. Server: Msg 4922, Level 16, State 1, Line 5 ALTER TABLE DROP COLUMN myDate failed because one or more objects access this column. Server: Msg 2705, Level 16, State 4, Line 2 Column names in each table must be unique. Column name 'myDate' in table 'dbo.myTable' is specified more than once.
Hello, I have hit the wall here...can't make sense of this one.
I have a script that creates a PRIMARY KEY constraint called PK_tblDRG CODE:
ALTER TABLE [dbo].[tblDRG] ALTER COLUMN [record_id] Uniqueidentifier NOT NULL Go ALTER TABLE [dbo].[tblDRG] WITH NOCHECK ADD PK_tblDRG PRIMARY KEY CLUSTERED ( [record_id] ) WITH FILLFACTOR = 90 ON [PRIMARY]
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PK__tblDRG]') and OBJECTPROPERTY(id, N'IsPrimaryKey') = 1) ALTER TABLE [dbo].[tblDRG] DROP CONSTRAINT PK__tblDRG
Suppose I have a table called "Languages" with two fields. One field is an Identity field that acts as the Primary Key. The second field is "LanguageName" which would naturally be "English", "Spanish", etc. What I want to do is put a constraint on the LanguageName field so that someone cannot enter the same name twice.Is it better to create an Index --> Create UNIQUE and use:a) Constraint?b) Index with Ignore duplicate key checked?Is there any benefit of one over the other for my purpose? Thanks.
I'm creating a table that contains information from two other tables. I'd like to have a constraint on some columns so that thay can only contain information that exists in the other two tables. This is what I got:
create table dbo.KUSE_Bills ( SERVICE_ID int IDENTITY(1,1) NOT NULL primary key, BILLDATE datetime NOT NULL, CNAME varchar(100) NOT NULL, SNAME varchar(100) NOT NULL, PRICE money NOT NULL, UNIT varchar(50) NOT NULL, NUMBER integer NOT NULL, BILLSUM money NOT NULL ) GO
I tried something like this:
create table dbo.KUSE_Bills ( SERVICE_ID int IDENTITY(1,1) NOT NULL primary key, BILLDATE datetime NOT NULL, CNAME varchar(100) NOT NULL, SNAME varchar(100) NOT NULL, PRICE money NOT NULL, UNIT varchar(50) NOT NULL, NUMBER integer NOT NULL, BILLSUM money NOT NULL
CONSTRAINT chk_cname CHECK (CNAME NOT IN ( SELECT CNAME FROM KUSE_Customer)) ) GO
I have a created a database with nearly 20 tables in it, so I cannot post all of my statements. I am having an issue though with two tables' referential integrity when it comes to foreign key constraints. I want to constrain them to cascade updates from the primary key tables, but I keep getting the error msg 1785
Introducing FOREIGN KEY constraint 'FK__PURCHASE___ITEM___64F971E5' on table 'PURCHASE_ORDER_LINE' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Here is the table with the primary key: create table MERCHANDISE ( ITEM_ID varchar (8) NOT NULL PRIMARY KEY, DESCRIPTION CHAR (60), STANDARD_PRICE MONEY,
[code]...
I have tried making an update trigger but it does not work.
What is the simplest way to add a unique constraint on a field of type varchar(7) that can allow any number of <NULL>'s?
I only want to ensure that when this field is updated, it is updated with a value that has not been used.
IF EXISTS (SELECT Project FROM tbProjects WHERE Project = @cProject) RAISERROR('Project number already used!',16,1) ELSE UPDATE tbProjects SET Project = @cProject WHERE ProjectID = @iProjectID GO
Also, I cannot allow the user to chante the project field value once it is set.
Is it possible to have a constarint between two tables based on a FK relationship and a value based on another column. For example to have a valid record in table b the TableA_ID value needs to exist in tableA and the charge Value can't be null. So row number 3 would be invalid in table B in this example.
TableA
IDCharge_Value 1100 2Null 34 4Null
TableB
TableB_IDTableA_IDSome other data 1 1 A 2 3 B 3 4 C