UNQIUE Constraint On String Column?
Jan 21, 2008
What do you guys think about creating a unique constraint on a string column in a database?
Currently, I'm enforcing uniqueness through the stored procedure that inserts rows into the table. E.g.
PROCEDURE addRow( name )
DECLARE r INT;
SELECT COUNT(*) INTO r FROM foo WHERE foo.foo_name = name;
IF r = 0 THEN
INSERT INTO foo (foo_name) values(name);
ELSE
// Not unique throw an error
END PROCEDURE
What do you guys think?
View 12 Replies
ADVERTISEMENT
Sep 30, 2014
We have a database where many tables have a field that has to be lengthened. In some cases this is a primary key or part of a primary key. The table in question is:-
/****** Object: Table [dbo].[DTb_HWSQueueMonthEnd] Script Date: 09/25/2014 14:05:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DTb_HWSQueueMonthEnd](
[Code] ....
The script I am using is
DECLARE@Column varchar(100)--The name of the column to change
DECLARE@size varchar(5)--The new size of the column
DECLARE @TSQL varchar(255)--Contains the code to be executed
DECLARE @Object varchar(50)--Holds the name of the table
DECLARE @dropc varchar(255)-- Drop constraint script
[Code] ....
When I the the script I get the error message Could not create constraint. See previous errors.
Looking at the strings I build
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] DROP CONSTRAINT PK_DTb_HWSQueueMonthEnd
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] Alter Column [Patient System Number] varchar(10)
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] ADD CONSTRAINT PK_DTb_HWSQueueMonthEnd PRIMARY KEY NONCLUSTERED ([Patient System Number] ASC,[Episode Number] ASC,[CensusDate] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
They all seem fine except the last one which returns the error
Msg 8111, Level 16, State 1, Line 1
Cannot define PRIMARY KEY constraint on nullable column in table 'DTb_HWSQueueMonthEnd'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
None of the fields I try to create the key on are nullable.
View 2 Replies
View Related
Jul 27, 2007
How do I prevent a column having empty strings entered into it. I want to allow
nulls but not allow empty strings.
Paul
View 2 Replies
View Related
Jul 23, 2005
How can you indicate that a FOREIGN KEY constraint references twocolumns in two different tables?"SQL Server Books Online" show an example of how to reference twocolumns in the SAME table:REFERENCES ref_table [ ( ref_column [ ,...n ] )Here is the error and the 'bad' SQL code:Server: Msg 8148, Level 16, State 1, Line 4More than one column FOREIGN KEY constraint specified for column'UserOrGroupId', table 'salesforce3.dbo.AccountShare'.CREATE TABLE salesforce3.dbo."AccountShare" ("Id" varchar(18) PRIMARYKEY , ... , "UserOrGroupId" varchar(18) CONSTRAINTFK_UserOrGroupId6349 FOREIGN KEY REFERENCES "User"(Id) REFERENCES"Group"(Id) , ... )
View 2 Replies
View Related
Dec 13, 2007
Hmm,
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
But subqueries are not allowed...
So how can I do it?
View 3 Replies
View Related
Apr 13, 2012
I have a requirement where one column of a table is supposed to have two foreign key constraints i.e. it can be referring to two different columns in two tables.
View 1 Replies
View Related
Jun 6, 2008
I like to use the management console to design tables, but have
been unable to figure out how to add a unique column constraint.
I have a primary key defined in col1 and want to make col2, char(10),
unique, but keep col1 as the primary key.
I have tried the Check constraint menu path, but do not know how
to write the expression.
If I go along the Indexes/Key path, I am forced to change the primary
key which I do not want to do.
Can anyone help?
TIA, Joe
View 5 Replies
View Related
Jul 20, 2005
Hi allWould there be a easy way to find the column name(s) which constitutea Primary constraint for a table through navigating the systemcatalogs.I found that the PK Constraint object in syscontraints is showing thecolid = 0.TIANorman
View 2 Replies
View Related
Sep 25, 2007
Hello !
I am using Microsoft SQL Server 2000
I am trying to drop a column that has a constraint, executing the script inside a transaction:
BEGIN TRANSACTION
ALTER TABLE MOPTeste DROP CONSTRAINT FK_IDMOPPais
ALTER TABLE MOPTeste DROP COLUMN IDMOPPais
COMMIT
If i dont commit the drop constraint, it wont let me drop the column
Solutions?
View 3 Replies
View Related
Aug 31, 2000
I receive the following error when creating a CHECK constraint that references another column. According to the good old Wrox SQL Server book, I'm using the correct syntax. Anyone have any ideas???
Thanks in advance!
Server: Msg 8141, Level 16, State 1, Line 1
Column CHECK constraint for column 'end_date' references another column, table 'Session'.
Here's an example of the script that I'm using:
CREATE TABLE Session (
session_key char(18) NOT NULL,
course_key char(18) NOT NULL,
site_key char(18) NOT NULL,
instructor_key char(18) NOT NULL,
start_date smalldatetime NULL,
end_date smalldatetime NULL
CHECK (end_date >= start_date)
)
.
View 1 Replies
View Related
Aug 18, 1999
How do I alter a column check constraint?
I have the table:
CREATE TABLE Mytable(
mykey integer,
mycol integer
CHECK(mycol BETWEEN 1 AND 2)
PRIMARY KEY(mykey))
How do I change the constraint to
CHECK(mycol BETWEEN 0 AND 2)
...without losing any data?
Thanks!
Jim
View 1 Replies
View Related
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
Dec 7, 2001
I can't seem to get the syntax correct for ALTERing an existing column with a default constraint. I've been to Help and BOL. There are examples that show how to use the ALTER command to add a column with a default constraint but not how to do it on an existing column.
Any help would be appreciated.
Sidney Ives
View 1 Replies
View Related
Jun 6, 2007
Can anyone please tell me how can i create a uniqueness contraint on part of column and index that part too. i.e.
consider the following table.
table A
Col1
furadfaf
fsradfasd
dddafadsf
hjfhdfjakdj
now i want only left three characters of the Col1 to be unique and indexed.
any idea ??????
View 5 Replies
View Related
Jul 16, 2004
I have a producer table with a nullable column that stores SSN's. In some cases producers inherit SSN's from other producers. These records will have a null producer.ssn and a record stored in a child table to track the inheritance. Anyway, I've found two techniques to enforce uniqueness on a nullable column and wanted to get opinions as to which was better. First, write a trigger. Second, create a computed column that has a unique constraint on it. The computed column would use the SSN if not NULL Else use the PK identity value of the record. EXAMPLE DML:CREATE TABLE test ( ssn CHAR(9) NULL, testId INT identity(1,1) NOT NULL, ComputedConstraint AS CASE WHEN ssn IS NULL THEN CAST(testId AS CHAR(9)) ELSE ssn END, UNIQUE (ComputedConstraint)) Any comments would be greatly appreciated.
View 6 Replies
View Related
Mar 17, 2004
I am importing data from a flat, comma delimited text file. It appears to properly import all the records and then on the last record it give me the error
INSERT statement conflicted with COLUMN FOREIGN KEY constraint for 'EOR_ITE_REF_EOR'.
Then it goes on to tell me the database, table and column in which the problem occured which is the first column in the table. It looks like it doesn't like the end of the file for some reason (EOR, end of record?) so I tried deleting the last record from the file and it still does it. I do have a file that I have imported that worked so I tried copying the last record of that file and pasting it into the last record of the file I wanted but that did not work either. The ends of file that works and the file that doesn't work look the same and I can find nothing on 'EOR_ITE_REF_EOR'. Any help would be appreciated.
View 1 Replies
View Related
May 18, 2015
Running an insert into a table where a column has a constraint for unique records
i have an autonumber pk that increments but numbers are not in sequence etc. if constraints are found
e.g.
10 records are inserted but only 2 are unique but there is a gap of 8 in the PK autoincrement value (it's like the unique records that were not inserted are still being recorded by the autoincrement).
View 1 Replies
View Related
May 5, 2014
I am very new to sql and I have got this doubt.
CREATE TABLE employee
{ EMP-ID VARCHAR UNIQUE,
DESIG VARCHAR UNIQUE,
SALARY INT };
Probably this is worst table ever created :).Now How to drop UNIQUE constraint on only column lets DESIG.
if i write
ALTER TABLE employee
DROP CONSTRAINT myuniqueconstraint;
will drop constraints on both columns which I dont want.
Any query that remove UNIQUE CONSTRAINT only on DESIGN column.
and one more clarification,
ALTER TABLE employee
MODIFY SALARY INT NOT NULL;
ALTER TABLE employee
ALTER COLUMN SALARY INT NOT NULL;
which of the above two is right query to add NOT NULL constraint to the above employee TABLE?
View 1 Replies
View Related
Nov 23, 2007
I don't immediately find if this is possible but hope someone can give me an answer:
is it possible to make a unique constraint over 2 columns but only when 1 column has a specific value ?
Example: table (tableid, instancetype, instancename, ..)
instancetype can be A or B
if it is A then instancename must be unique
but for B instancename is not unique as these are copies from A
only solution I can think of is to make a trigger on an insert to check what the instancetype is and do a select to see if the name already exists in the table or not..
are there other solutions to make a constraint like this ?
Aeneas.
View 1 Replies
View Related
Oct 29, 2005
Is it possible to create a unique constraint to a column from anothertable? For example:tb_current:current_names--------------aaabbbtb_new:new_name--------cccNow I want to create a constraint on tb_new.new_name to be unique withrespect to tb_current.current_names. However, tb_new.new_name shouldnot be unique to itself. So I should not be able to insert 'aaa' totb_new.new_name. But I should be able to insert 'ccc' totb_new.new_name.Here's the script to reproduce this example:create table tb_current(current_names varchar(10))create table tb_new(new_name varchar(10))insert tb_current values ('aaa')insert tb_current values ('bbb')insert tb_new values ('ccc')select * from tb_currentselect * from tb_newinsert tb_new values ('aaa') -- this should NOT be allowedinsert tb_new values ('ccc') -- this should be allowed
View 3 Replies
View Related
Oct 1, 2007
Hello!
I am trying to alter a table adding a column with foreignkey constraint. The table that holds the primary key in that relation has data, so i am not being able to execute the alter statement.
This is the error:
Server: Msg 547, Level 16, State 1, Line 1
ALTER TABLE statement conflicted with COLUMN FOREIGN KEY constraint 'FK_MOPAeroportoICAO_IDMOPAlimentacaoFerroviaTipo'. The conflict occurred in database 'MOP', table 'MOPAlimentacaoFerroviaTipo', column 'IDMOPAlimentacaoFerroviaTipo'.
This is the script:
ALTER TABLE MOPAeroportoICAO
ADD IDMOPAlimentacaoFerroviaTipo [int] DEFAULT 0 NOT NULL
CONSTRAINT [FK_MOPAeroportoICAO_IDMOPAlimentacaoFerroviaTipo] FOREIGN KEY
REFERENCES MOPAlimentacaoFerroviaTipo (IDMOPAlimentacaoFerroviaTipo)
How can i turn of check when i add the foreign key ?
Thanks in advance
View 1 Replies
View Related
Aug 21, 2006
I need to create constraint in column to add only alphabet .
like "adc" ,"sdfsd" and not "1234adfd".plz reply soon.
View 4 Replies
View Related
Dec 19, 2007
When generating a check constraint to guarantee that a character column cannot be blank is it best to use comparison operators such as col1 <> '' or to use LEN(col1) > 0? Note that the column in marked as not nullable.
View 5 Replies
View Related
Nov 17, 2006
Hi,
I have a table with one of its column VARBINARY(MAX).
I want to make sure that the values in this VARBINARY(MAX) column is unique.
SQL Server doesn;t allow to create Unique Constraint over VARBINARY fields - whats the best workaround for ensuring uniqueness on VARBINARY columns.
Thanks,
Loonysan
View 1 Replies
View Related
May 22, 2008
how can setup constraint for the column in table in database ??
and what will sould write in the (BLOCKED EXPRESSION field ??
View 5 Replies
View Related
Mar 9, 2000
I cannot figure out how to add a default constraint to an existing column. The syntax I'm using is :
ALTER TABLE table_name WITH NOCHECK
ADD CONSTRAINT column_name DEFAULT (0)
This gives me a syntax error.
The column was originally added with a default constraint of 1 to a 2.6 million row table.
I dropped the existing constraint and need to add the new default constraint of 0 for that column.
Anyone have any ideas? Thanks in advance.
View 2 Replies
View Related
Mar 16, 2004
I need to alter the datatype of a column from smallint to decimal (14,2) but the column was originally created with the following:
alter my_table
add col_1 smallintNot Null
constraint df_my_table__col_1 default 0
go
I want to keep the default constraint, but i get errors when I try to do the following to alter the datatype:
alter table my_table
alter column col_1 decimal(14,2)Not Null
go
Do I need to drop the constraint before I alter the column and then rebuild the constraint? An example would be helpful.
Thx
View 1 Replies
View Related
May 5, 2015
I have a table named [New Item] and created a default constraint on a column, and i wanted to change the data type of the column using the query
alter table [new item]
alter column pcs_qty decimal(15,2) not null
but the name of the default constraint is 'DF__New Item__Pcs_Qt__2D12A970' and i am not able to delete the constraint because it contains a space in between.Is there any work around for this.
I tried to delete the constraint by using the query
alter table [new item]
drop constraint 'DF__New Item__Pcs_Qt__2D12A970'
but I am getting the exception,
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'DF__New Item__Pcs_Qt__2D12A970'.
View 2 Replies
View Related
Feb 18, 2006
Hi there,
I have a stored procedure which i pass a number of parameters into. One of these parameters is staffNo (only passed this in because i couldn't execute the query without it). The thing is this field can be Null, but when trying to pass null into it it comes up with an Foreign Key conflict. staffNo is a foreign key within the table i'm inserting the data into.
This is the error i get:
"INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'PropStaffFK'. The conflict occurred in database 'DewMountain', table 'TblStaff', column 'staffNo'. The statement has been terminated. The 'PropertyAdvert' procedure attempted to return a status of NULL, which is not allowed. A status of 0 will be returned instead. "
Does anyone know of away around this? how to pass a null value to the stored procedure without it causing this error.
Thank you
Melanie
View 13 Replies
View Related
Apr 5, 2004
Hi all,
I am trying to add a unique index/constraint on a column that allows NULL values. The column does have NULL values and when I try to create a unique constraint, I get the following error.
CREATE UNIQUE INDEX terminated because a duplicate key was found for index ID 9. Most significant primary key is '<NULL>'.
Are'nt you allowed to create a UNIQUE constraint on a NULL column? Books Online says that you are allowed to create a unique constraint on NULL columns, then why am I getting this error.
Any help would be appreciated.
Thanks,
Amir
View 8 Replies
View Related
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
Aug 6, 2007
I have created a simple package to load an Excel Spreadsheet into a SQL Server table. There is a one to one relationship between the columns in the .xls file and the columns in the DB record. I am getting integrity constraint errors when I try to load all numeric data from the spreadsheet (defined as Category General in excel, not defined as numeric but consisting of all numeric characters) into a column defined as (nvarchar(20), not null) in SQL Server Management Studio. There are no constraints on the column.
I have been able to temporarily bypass the offending rows, but I do need to load them into SQL Server. The problem column has a mixture of data, two examples would be: N255, 168050. It's the 168050 value that's causing the Task to bomb. How can I get this loaded into my table ?
I am running the package from within MS Visual Studio 2005 Version 8, Excel is version 2003 (11.8120.8122) SP2
Thanks,
Chris
View 15 Replies
View Related
Jan 20, 2004
Cannot find an answer to this in previous posting, though there are similar topics.
My primary key "ID" requires a value (is not nullable), and not explictly providing it with one when I update a new record gives the following error:
Cannot insert the value NULL into column 'ID', table 'AdClub.mediaq.News'; column does not allow nulls. INSERT fails.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'ID', table 'AdClub.mediaq.News'; column does not allow nulls. INSERT fails.
However, trying to stuff that field with a recordCount+1 value (or any value), I get this error:
Violation of PRIMARY KEY constraint 'Primary Key'. Cannot insert duplicate key in object 'News'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'Primary Key'. Cannot insert duplicate key in object 'News'.
Cannot figure this one out. The value I'm providing for that field is known to be unique, but the SQL Server spits it out each time.
Is there a way to have the ID primary field automatically update with a new value when a new record is generated? This is how I used to do it in Access, but cannot find a similar feature in SQL Server. I'm sure I'm missing something simple, but right now I'm stuck in this "Catch-22" situation.
Please help!
View 5 Replies
View Related