I am working with an evaluation copy of SQL Server 2000 for the first
time; my DB experience lies with MS Access.
I have a simple table in SQL Server (tblCompany) that has a field
called "Ticker." When new company stock tickers (i.e., MSFT for
Microsoft) are entered into the field, I'd like them in all
caps--whether the user types msft, Msft, MsFt, etc. In Access, this
was easy--simply set the Format to ">" in table design view.
In SQL Server Design Table view, I've clicked on "Manage Constraints"
and put the following code in that I found elsewhere:
([Ticker] = upper([Ticker]))
I then checked all three boxes below: "Check existing data on
creation," "Enforce constraint for replication," and "Enforce
constraint for INSERTs and UPDATEs." The first one, "Check existing
data..." is checked as I've already entered in some data in the field
in lowercase to see if the check constraint would go back and change
it to Upper Case--this because I'm wanting to ultimately migrate a
table from Access to SQL Server and ensure that all Tickers are in
Upper Case.
I'm able to do this and then save the table design with changes; but
every time, I then go and look at the table data to see if the check
constraint was applied, and each time it is not; then, I go back to
"Manage Constraints" and find that the "Check existing data..." box is
unchecked. I've gone through this SEVERAL times.
Hoping this is something simple. Apologize for my "newbieness." I've
got a "For Dummies" book in front of me as well as numerous Internet
windows open, trying to figure this out. Have checked books online on
the MSFT site as well to no avail.
Hi, I am developing a database for my company in SQL server 2000 and I have some few problems. Firstly.
I have a customers table and orders table in my DB:
Customers Orders --------- ------ CustID (primary key) ----------------< CustID . ^ ProductID . | Quantity . | . . | . etc. | etc. | relationship (one to many)
What I want to do is: 1) to be able to delete a Customer and automaticaly SQL server delete all the orders that this customer done from the Orders table. 2) If for some reason the CustomerID changes, SQL should be able to automaticaly update the necessary fields with the new values in the Orders table. Finally, 3) I want to be able to insert a new customer that has an order and update both the Customers table and Orders table automaticaly. e.g
CustID Name Address ProductID Quantity etc. ------ ---- ------- --------- -------- ---- 10-003 John London 33-25 2 ...
Such a kind of insert should add automaticaly the following entries in the two tables:
Customers Orders --------- ------ CustID (10-003) CustID (10-003) Name (John) ProductID (33-25) Address(London) Quantity (2) . . . . etc. etc.
A friend of mine told me that this can be done using Foreign Check constraints in SQL server. But I do not know what to do.
I am Trying to add a check constraint that if the paymenttotal is 0 the column is allowed to have null and if its greater then 0 it is not allow to have null. Here is what I have so far but i get some syntax errors, See if you can see what im doing wrong and how to get this to be valid. Thanks heres what I got so far
Code:
ALTER TABLE Invoices WITH CHECK PaymentDate SMALLDATETIME NULL, CHECK (PaymentTotal = 0) PaymentDate SMALLDATETIME NOT NULL, CHECK (PaymentTotal > 0)
I also had this before i changed it to that and I got syntax erros as well but i dunno which is closer.
I would like to establish a constraint that extablishes one to one relation between ID1 and ID2. Meaning in the above example ID2 =122 should not be assingned to any ID1 other than 1. (For example, I should not be able to insert another row like ID1EffDateExpDateID2ID2_Location 41/1/200712/31/9999122ABC)
Beacause this table is maintained in a manual way, sometimes the ID2 which has already been assigned an ID1 is being assigned to another ID1.
What kind of constraint or rule will avoid this scenerio.
I have an Account table as well as a Bank table. The bank table has a total assets field. There is a foreign key in Account referencing Bank.
What I need is a check constraint that verifies that the total sum of the account balances for a particular bank is less than that banks total assets.
I've been thinking about this one for a while but it's just confusing me. How do I create the expression in the constraint for this? Currently I am using SQL Server Management Studio Express so I'm creating this constraint with the gui.
Hello, I want to write a unique constraint that applies to more than one column. What I mean is that the uniqueness should be that if column A is 5 and column B is 3 no other row where A and B has those values can exist.
Do I write this as a check constraint ? Or how do I do it ?
Also, is there anyone who knows some good reading on how to use Link Tables (many to many relations) in MS SQL Server ?
I have a question concerning setting up data integrity checks in SQL Server.
I have a table that lists "Groups" to which an Entity belongs. The Entity can belong to multiple Groups. Every entity has 1 and only 1 of its Groups designated as the "Primary Group". Based on this, my table contains multiple records for each Entity. Each record describes 1 Group of which the Entity is a member. In this record, there is a bit field indicating whether the Group is the "Primary Group".
In other DBMS's I have implemented a check constraint on the "Primary Group" column to enforce the business rule that "a Entity may have one and only one Primary Group". I am aware now, that in SQL Server 7, I must implement this rule as a trigger, or in the client or data services layers.
Does anyone know if SQL Server 2000 will allow me to write such a check constraint?
Hi, I´m facing teh following situation:This are just sample table names, but should do for discussingpurpouses.Create table Invoice(InvoiceID Integer Not Null,CustomerType Integer Not Null,CustomerCode Integer Not Null,Amount DECIMAL(10,2) Not Null,.................)Create Table Type1Customer(CustomerCode Integer Not Null,...............................)Create Table Type2Customer(CustomerCode Integer Not Null,...............................)I need to add a way to restrict the CustomerType and CustomerCode,in the Invoice table to the correct values.This means that if customerType equals 1 the customerCode should bechecked against Type1Customer and if customerType equals 2 thecustomerCode should be checked against Type2Customer.I succesfully created a check constraint. That ensures that the validvalues exists when the rows in the Invoice table are inserted orupdated, but doesn´t prevent from deleting records from tablesType1Customer and Type2Customer that are referenced from the Invoicetable.Are triggers the only way to go?Thanks in advanceSebastián streiger
I have tables that are replicated using transactional and merge replication. As a result I am unable to use automatic identity management as transactional replication doesn€™t seem to understand it.
Therefore I have implemented a version of the automatic mechanisms that seems to work in a hybrid environment. It is based on a central table that holds the maximum identity for each table that has been issued to date. Valid identity ranges are issued to each publisher and subscriber as needed in a similar way to the automatic mechanisms and tables are reseeded as needed.
I want to enforce the ranges in a similar way to the automatic mechanism using a check constraint similar to this:
alter table [dbo].[test1] with NOCHECK add CONSTRAINT repl_identity_range_48DF13ED_D503_4F5C_AED9_4E504D03E752 check NOT FOR REPLICATION (([id] > 10001 and [id] <= 20001) or ([id] > 50001 and [id] <= 70001))
This works OK on a client subscriber, but if the change is made on the publisher, then the alter statement itself is replicated out to all clients €“ which is not what is wanted. I have traced the automatic mechanisms using profiler and they issue an alter statement as above €“ following dropping of the constraint €“ but the check constraint isn€™t replicated. I can't see how this is achieved.
How do I stop the check constraint being replicated?
The article property schema option can be set to stop replicating check constraints, but this seems to have no effect. If the publication property replicate_ddl is set to 0 then I do see the behaviour that I want. However, I do need to be able to replicate most schema changes due to upgrades etc €“ so this doesn€™t look like a viable option €“ except possibly for the transactional publication.
When our DB was converted from 6.5 to 7, the some column check constraints changed to table constraints.
Is there a way to change them back, short of rebuilding the table? I can't find a syntax to add a column constraint without adding a column. Some of the affected tables contain millions of rows, so I'd rather not rebuild them.
When I create a test table with a column and a table check, I see that in sysconstraints "colid" and "status" are different, and in sysobjects "info" and "status" are different. I am leary of tweaking the database catalog though. Heck, this is SQL 7; I don't even know if these are real tables or mirages.
create table zzzfoo ( myname char(30) check (myname in ('foo', 'bar')), myfuzz char(30), check (myfuzz in ('cotton', 'wool', 'linen')) )
select sc.* from sysconstraints sc, sysobjects so where sc.id = (select id from sysobjects where name = 'zzzfoo') and sc.constid = so.id and so.type = 'C'
Let's say I create a multi-statement function like this:CREATE FUNCTION dbo.Test ()RETURNS @res TABLE (N int NOT NULL CHECK (N >= 0))ASBEGININSERT INTO @resSELECT 1RETURNENDThat works fine. Then I make a change in the function's body, replace theCREATE FUNCTION with ALTER FUNCTION, and execute the batch. I get an error:Server: Msg 3729, Level 16, State 3, Procedure Test, Line 9Cannot ALTER 'dbo.Test' because it is being referenced by object'CK__Test__N__5D2E32EB'.Indeed, if I look at the list of dependencies for the function in QA'sobject tree, I can see the check constraint referenced in the errormessage.ALTER FUNCTION works fine if I don't specify the CHECK constraint in thedefinition of the @res table.So it seems that the only way to modify such a function is to drop andrecreate. Is that a known behavior? Is there any particular reason for it?Thanks.--(remove a 9 to reply by email)
I have one table like below Test table. My requirement is to create constraints to confirm <g class="gr_ gr_331 gr-alert gr_gramm Grammar only-ins replaceWithoutSep" data-gr-id="331" id="331">uniqueness</g> of STID value 101 with LN.
likeÂ
ID - LN - STID 1 - 'ABC' - 101 Â ---- Valid Row 2 - 'ABC' - 202 --- Valid Row 3 - 'ABC' - 202 --Valid Row (as I want only unique when LN = 'ABC' with STID = 101) 4 - 'ABC' - 101 -- Invalid Row (As I want uniqueness base on LN and STID = 1011)
create table dbo.Test ( ID int identity, LN varchar(50), STID bigint )
Is this possible with constraints as I don't want to use <g class="gr_ gr_1041 gr-alert gr_gramm Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="1041" id="1041">trigger</g>.
I have come across this problem with SQL server both on 2000 and 2005. I am stating an example here.
I have two partitioned tables and a view on top of both tables as below: create table [dbo].[Table_1] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK NOT FOR REPLICATION ([TableID] BETWEEN 1 AND 999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO
create table [dbo].[Table_2] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK NOT FOR REPLICATION ([TableID] BETWEEN 1000 AND 1999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO create view TableView as select * from Table_1 union all select * from Table_2 GO
Note the NOT FOR REPLICATION clause on the check constraint on the TableID column.
I then ran the query execution plan for the following query on both SQL server 2000 and 2005. select * from TableView where TableID = 10
On both the versions the execution plan shows and Index seek on both the tables in the view. This means that my partitioning is not working. If I remove the primary key constraint from the TableID column, the same query on the view shows a table scan on all the underlying tables. This is even worse.
Next, create the same tables and views again, now without the NOT FOR REPLICATION clause on the check constraint as show below: create table [dbo].[Table_1] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK ([TableID] BETWEEN 1 AND 999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO
create table [dbo].[Table_2] ( [TableID] INTEGER PRIMARY KEY NONCLUSTERED CHECK ([TableID] BETWEEN 1000 AND 1999), [AnyOtherColumn] int NOT NULL , ) ON [Primary] GO
create view TableView as select * from Table_1 union all select * from Table_2 GO
Now run the query execution plan for the same query again.
select * from TableView where TableID = 10
This time you would see that it does an index scan only on the first parititon table. This time it proves that the partitioning works.
I would like to know why does the NOT FOR REPLICATION clause in the check constraint make such a huge difference?
I'm putting a process together to run a DBCC CHECKCONSTRAINTS process against copies of client databases.The author application doesn't set the constraints as trusted, and therefore we need to check the integrity of the data.
The problem is that some of the Check constraints have a definition that is longer than 4,000 characters.When this is the case, DBCC CHECK CONSTRAINTS fails.One option is that I write a cursor to select the constraints that have a definition less than 4,000 characters and then call the DBCC command for those particular constraints. However, I'd prefer a more elegant approach - ideally a way to run DBCC CHECKCONSTRAINTS against all constraints regardless of the length of the definition
I have Variable , data source and conditional transformation which checks the count(*) if the count == 0 then I connect an script component and change variable to false(initial it is True) and write into a log file...
Then I check that variable on predence constarint at workflow if variable==True then success. BUT Whenever I run the package my dataflow gets green even the condition does not meet like count==0 . So my variable's value is "False". Actually if the condition doesnt meet then my script shouldnt work. Am I missing something???
I know this is probably a flick of a switch but I cannot figure out which switch. Setup is SQL Server / Stored Procedures / DAL / BLL(skipped for testing) / PL. The stored procedure queries from only one table and two columns are ignored because they are being phased out. I can run the stored procedure and preview the data in the DAL but when I create a page with an ODS linked to the DAL and a GridView I get this error. I checked every column that does not allow nulls and they all have values. I checked unique columns (ID is the only unique and is Identity=Yes in the table definition). I checked foreign-key columns for values that are not in the foreign table and there are none. Any ideas why do I get this? Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Hi, I am getting the above error when trying to load a report into my Web Application, I have tracked the error down to one specific field in my database. Even though this field is a NVarChar field and is of size 30 it would seem that there is an issue returning the value from the field. I can write it into the database no problems but when I try to get it out of the database it returns the above error. e.g MOB 401.908.804 - Fails 0401.907.324 - okay 8239 9082 (pager) - fails Anyone got an idea on how to fix this???? Regards.. Peter.
I'm using MS SQL 2000 with enterprise manager I have a customers table called high_customer, it has a primary key called IDI have an invoices table called high_invoices, it has no primary keys but it does have a column for customer ID.I want to set it so if a customer is deleted from the customers table, any invoices with that customerID are deleted from the invoices table.Do I need to specify a constraint? If so how do I do it in enterprise manager.Thanks
Hi, I have the following problem: I have a table called Jobs with the fields: JobNumber, Name, Customer, ... And a table called Customers with the fields: ID, Name, Address, ... Obviously Jobs is linked to Customers with the Customer<->ID fields. I want to set it up so that if a Customer is deleted, then any Jobs that had that customer listed now have the Customer field set to NULL. Can I do this with a constraint, or will I need to use a trigger? Cheers,Little'un
Hello, I am not a DBA and I need to do the following. I have 2 tables A and C and both have a common fileds say emp.Emp is pkey in C . There can be a record in C but not in A.If a record is inserted in A then it checks for the same employee info in C .If not found it do not allow to insert a record in A. How to go for it? Thanks!
Hiya peops im creating a constraint using enterprise manager for 1 of my tables n was wondering how u constructively create a constraint expression, there is a specific style,right??
i have added my tables and defined foreig keys and primary keys for my table, but when i try to put the data it gives me some error reagards to parent key..and it wont let me drop the table... can anybody tell me how to drop the foregin key..i have tried (
ALTER TABLE module DROP CONSTRAINT ATTENDANCEID_FK;) this formula and it wont work,
heres my tables and relationships:
CREATE TABLE ATTENDANCE (ATTENDANCEID char(4) NOT NULL, StudID char(4) NOT NULL, ModuleID char(4) NOT NULL, Week1 VARCHAR(10), Week2 VARCHAR(10), Week3 VARCHAR(10), Week4 VARCHAR(10), Week5 VARCHAR(10), Week6 VARCHAR(10), PRIMARY KEY (ATTENDANCEID));
ALTER TABLE ATTENDANCE ADD FOREIGN KEY (studID) REFERENCES student(studID); ALTER TABLE ATTENDANCE FOREIGN KEY (moduleID) REFERENCES module(moduleID));
insert into ATTENDANCE values ('F1','A1','E1','Yes','Yes','Yes','Yes','Yes','Yes'); insert into ATTENDANCE values ('F2','A2','E2','Yes','No','Yes','Yes','No','Yes'); insert into ATTENDANCE values ('F3','A3','E2','Yes','Yes','Yes','No','Yes','Yes'); insert into ATTENDANCE values ('F4','A4','E2','Yes','Yes','Yes','Yes','No','Yes'); insert into ATTENDANCE values ('F5','A5','E1''Yes','Yes','No','Yes','Yes','Yes'); insert into ATTENDANCE values ('F6','A6','E2','Yes','Yes','Yes','Yes','Yes','No'); insert into ATTENDANCE values ('F7','A7','E1','Yes','Yes','Yes','Yes','No','No'); insert into ATTENDANCE values ('F8','A8','E2','Yes','Yes','Yes','No','Yes','Yes'); insert into ATTENDANCE values ('F9','A9','E3','Yes','Yes','No','Yes','Yes','Yes');
CREATE TABLE MODULE (ModuleID char(4) NOT NULL, ATTENDANCEID char(4) NOT NULL, ModuleName varchar(45), ModuleCode varchar(6), PRIMARY KEY (ModuleID));
ALTER TABLE MODULE ADD FOREIGN KEY (attendanceID) REFERENCES attendance(attendanceID);
insert into MODULE values ('E1','F1','Workshop Research and Project Implementation','Im3023'); insert into MODULE values ('E2','F2','Advanced Database Development','SD3042'); insert into MODULE values ('E3','F3','Advacned Information Systems Develpment','SD3043');
I am fairly new at SQL and also new to this forum. So I don't know if this topic belongs here or not.
But anyways, I found this tutorial online. However, I am having trouble completing it. Can someone please help me?
Given the following table definitions:
CREATE TABLE USERS ( USERID CHAR(5) PRIMARY KEY, NAME VARCHAR(30), RATING CHAR(1) CHECK (RATING IN (A, B,C,D) )
CREATE TABLE ITEMS ( ITEM_NO NUMBER PRIMARY KEY, DESCRIPTION VARCHAR(50), OFFERED_BY CHAR(5) REFERENCES USERS(USERID) ON UPDATE CASCADE ON DELETE CASCADE, START_DATE DATETIME, END_DATE DATETIME, RESERVE_PRICE NUMBER )
CREATE TABLE BIDS ( USERID CHAR(5) REFERENCES USERS ON UPDATE CASCADE ON DELETE SET NULL, ITEMNO NUMBER REFERENCES ITEMS(ITEM_NO) ON UPDATE CASCADE ON DELETE CASCADE, BID NUMBER, BID_DATE DATETIME, PRIMARY KEY(USERID,ITEMNO,BID_DATE) )
Directions: Indicate whether the statement is accepted or rejected; and if accepted indicate its effects. Evaluate each statement INDEPENDENTLY.
1) INSERT INTO ITEMS VALUES(1009, Red Bicycle,U01,1999-01-08, 1999-02-10, 30) 2) UPDATE ITEMS SET ITEMNO=1008 where ITEMNO=1001 3) DELETE FROM ITEMS WHERE ITEMNO=1005 4) INSERT INTO ITEMS VALUES(1010, Green Bicycle,U07,1999-01-08, 1999-02-10, 30) 5) UPDATE BIDS SET ITEMNO=1011 WHERE ITEMNO = 1001 6) DELETE FROM USERS WHERE USERID=U01 7) UPDATE ITEMS SET ITEMNO=1020 WHERE ITEMNO=1001 8) DELETE FROM BIDS WHERE BID > 1001
ORDER_ITEM (OrderSK, ItemNumber, Qty, ServiceSK, UnitPrice) SERVICE (ServiceSK, Description, UnitPrice)
How could I modify the database structure to enforce the data constraint that ORDER_ITEM.UnitPrice must be equal to SERVICE.UnitPrice for the corresponding service.