Showing posts with label field. Show all posts
Showing posts with label field. Show all posts

Sunday, March 25, 2012

Check mail and password with sp

How can I write a stored procedure with SQL 2000 Server to check an e-mail and password entered by the user, and if both exist select the Id field ?

Table Users:
UserId
First_name
Surname
Age
E-mail
Password

If it is possible I would like to know how can I write the error messages in three cases: If E-mail doesn't exist, if password doesnt exist and if both doesnt exist. And I would like that those messages would be able to appear on the website application.

ThanksMay check Planet SC (http://planet-source-code.com) for any CE.|||Ok thank you

Thursday, March 22, 2012

check if field contains numeric character

How can I select all of the rows of my table for which a certain
field's value contains other characters than a-z and A-Z (non alpha
string) ?
Thank youWhere Column like '%[0-9]%'
Look up "Pattern Matching in Search Conditions" in BOL for more information.
<samuelberthelot@.googlemail.com> wrote in message
news:1148478170.488497.325220@.j33g2000cwa.googlegroups.com...
> How can I select all of the rows of my table for which a certain
> field's value contains other characters than a-z and A-Z (non alpha
> string) ?
> Thank you
>|||If it does not help ,please post your actual data + expected result
create table #t (c1 varchar(20))
insert into #t values ('cdjdfj')
insert into #t values ('cd4jdfj')
insert into #t values ('fh')
insert into #t values ('1525')
insert into #t values ('1jj')
insert into #t values ('jkk')
select * from #t where c1 like '%[0-9]%'
<samuelberthelot@.googlemail.com> wrote in message
news:1148478170.488497.325220@.j33g2000cwa.googlegroups.com...
> How can I select all of the rows of my table for which a certain
> field's value contains other characters than a-z and A-Z (non alpha
> string) ?
> Thank you
>|||found out, had to use the PATINDEX function|||Uri Dimant wrote:
> If it does not help ,please post your actual data + expected result
> create table #t (c1 varchar(20))
> insert into #t values ('cdjdfj')
> insert into #t values ('cd4jdfj')
> insert into #t values ('fh')
> insert into #t values ('1525')
> insert into #t values ('1jj')
> insert into #t values ('jkk')
>
> select * from #t where c1 like '%[0-9]%'
>
What about :
insert into test values ('!"=A3$%^&*()_')
Try this instead:
select * from #t where c1 like '%[^A-Z]%'=20
Jamie.

Tuesday, March 20, 2012

Check if a field exists before ADD a new column.

Hi All.
We have some scripts adding columns to tables. Is there a simple way to
check if the column are there already in the table before running the ADD
command. Just like you get on the table when scripting it?
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[CalDates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
Thanx all
ghHello,
You can use something like this:
IF NOT EXISTS (SELECT * FROM syscolumns
WHERE id=OBJECT_ID('TableName') AND name='ColumnName')
[...]
Razvan|||if col_length('tb','col') is null
print('col does not exist in tb')
-oj
"Geir Holme" <geir@.multicase.no> wrote in message
news:uA2GTzcPGHA.1532@.TK2MSFTNGP12.phx.gbl...
> Hi All.
> We have some scripts adding columns to tables. Is there a simple way to
> check if the column are there already in the table before running the ADD
> command. Just like you get on the table when scripting it?
> if exists (select * from dbo.sysobjects where id =
> object_id(N'[dbo].[CalDates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
>
> Thanx all
> gh
>

Check if a caractere exists in a SQL field

Hi everybody ,
I would like with a Stored procedure check if a caracter exists in a string stored in a SQL server field.
Example :
My field contains the caracters "ABCDEF" ,
I would like to check if "C" is in this string.
Tank Uselect charindex('C', 'ABCDEF') which would return 3. If the first expression is not found in the second, it returns zero.|||Thanks joan but i would like to make the expression 2 a variable wich contains my column name

Remeber the syntax must respect syntax of stored procedure

This is my stored procedure code :
@.level is the caracter i search
@.droits is the caracters contained in my field

IF (@.Level <> "nothing")
BEGIN
SELECT @.droits=droits FROM USERS WHERE UserID=@.UserID
IF NOT SELECT charindex(@.Level, @.droits)


BEGIN
SELECT Progress=2,Errormsg="Pas l'droits."
RETURN
END
SELECT @.AccessNumber = @.AccessNumber + 1
UPDATE USERLOG SET Accessdt=GETDATE(),AccessNumber=@.AccessNumber WHERE SessionID=@.SessionID
SELECT Progress=0,userID=@.userID
RETURN
END

can you help me please ?|||DECLARE @.pos
IF (@.Level <> "nothing")
BEGIN
SELECT @.droits=droits FROM USERS WHERE UserID=@.UserID
SELECT @.pos = charindex(@.Level, @.droits)
IF @.pos > 0
BEGIN
SELECT Progress=2,Errormsg="Pas l'droits."
RETURN
END

SELECT @.AccessNumber = @.AccessNumber + 1
UPDATE USERLOG SET Accessdt=GETDATE(), AccessNumber=@.AccessNumber WHERE SessionID=@.SessionID
SELECT Progress=0,userID=@.userID
RETURN
END|||It works

Thank U guy : ))

Check for Primary Key before Inserting New Record

Hi,

Can someone please tell me the best practices for checking the primary key field before inserting a record into my database?

As an example I have created an asp.net page using VB with an SQL server database. The web page will just insert two fields into a table (Name & Surname into the Names table). The primary key or the Names table is "Name". When I click the Submit button I would like to check to ensure there is not a duplicate primary key. If there is return a user friendly message i.e. A record already exisits, if there no duplicate, add the record.

I guess I could use try, catch within the .APSX page or would a stored procedure be better?

Thanks

Brett

one way you could do this is write a stored proc where you can check :

CREATE PROC ...

@.intResult INT OUTPUT

SET @.intResult = 0

IF NOT EXISTS (SELECT <col> FROM <table> WHERE <condition>

BEGIN

-- do the insert here

-- SET @.intResult to 1

END

Now in your application check for the value of intResult. If its 1 the INSERT was successful. If it was 0 the record already exists. You can take this further and also return any error messages.

|||

Thanks for the information.

Please can you let me know how can I check in my ASP.NET page the value of intResult?

Regards,

Brett

|||

ndinakar wrote:

Now in your application check for the value of intResult. If its 1 the INSERT was successful. If it was 0 the record already exists. You can take this further and also return any error messages.

Return Codes are not needed in languages supporting exceptions. Instead, throw an exception from your SP within SQL Server ...

IF EXISTS(SELECT * FROM <tb> WHERE <pk> = @.pk) BEGIN
RAISERROR('A Document with a number of %s already exists.', 16, 2, @.pk)
RETURN
END

In the ASP code, use a TRY/CATCH around the Execute method. If the error returned is a user defined error (50000), wrap the message in your own exception and send it directly back to the client.

|||

Thanks again for your help, could you please post me an example of how the code for the Try/Catch would look in ASP.NET using VB.
Regards,

Brett

|||check out the recent articles in my blog..I have some sample code that uses Try/Catch block's.
|||

I have read your article but I still don't understand how I can check the RAISERROR from the stored procedure. I then want to display an error to the user saying for example "Duplicate Name Found" if the RAISERROR occurs but if the record is added I would like a message saying "Record Added".

Are there any book you can recommend that deal with ASP.NET & SQL Stored Procedures.

|||I dont have sample code but am sure you;d find it if you google.

Check For Null Value

Hello,

I have to check for a value of NULL in my field and keep getting a syntax error.

What have I done wrong?

=SUM(IIF(Fields!new_status.value IS NULL, CInt(Fields!Total_NotRec.value), 0))

Is this Excel or Access or something?

|||

Look into the IsDBNull() method (instead of using IS NULL). Use IS NULL within a SQL statement to check for null. Use IsNull() within a SQL statement to return a different value if the field is null. Use IsDBNull() within your VB code to check if a database field is null.

Also, if you're using a DataTable there will be a boolean method for each nullable column called Is[ColumnName]Null().

|||

In SRS, they have a function IsNothing.
When I wrapped the IsNothing function around this, I got a sum of 0.

SUM(IIF(Fields!new_rpcstatus.value IS NULL, CInt(Fields!Total_NotRec.value), 0))

Is there any other way to check for the NULL value?

|||

Hi,

From your description, you are unable to calculate the total value

I'm not sure how do you handle with IsNothing function? Have tried the following expression?

=SUM(IIf(IsNothing(Fields!ANYFIELD.Value),0,Fields!ANYFIELD.Value))

OR

=SUM(IIf(Fields! ANYFIELD.Value is nothing, 0, Fields! ANYFIELD.Value))

If the issue still exists, please use IIF function to check each row's value, to see if it matches the conditions.

Thanks.

Monday, March 19, 2012

Check for Duplicate values in Access

Hi, I'm creating a database that needs to check a value in a text field =
=
called JobCreate in a form called frmJobCreated against a table called =
tblJobCreated which has a whole list of job numbers in a field called =
JobNo, then come back with a message telling the user if there is a =
duplicate value...any help would be greatly appreciated,,thanks, FraserPlease, post DDL, sample data, and specify expected results.
Are you trying to report duplicate values, prevent them from being inserted
or what?
ML|||Hi, sorry for my ignorance but I'm quite new at databases what is DDL?
I'm trying to tell the user that a job number is already created if they
enter a duplicate number in the form that is already held in another
table, so it will display a message box telling them this, thanks
*** Sent via Developersdex http://www.examnotes.net ***|||Hi
First of all, This is not the right forum because there is a dedicated forum
for access.
well. Use primary key (SOME THING LIKE SELECT COLUMN WHILE DESIGININGG AND
RIGHT CLICK SELECT PRIMARY KEY) in access on the column so that it will
prevent and throws an error. you can customise your error using VBA.
You have to use VBA because you are not using SQL SERVER 2000
Regards
R.D
--Knowledge gets doubled when shared
"Fraser Hetherington" wrote:

> Hi, sorry for my ignorance but I'm quite new at databases what is DDL?
> I'm trying to tell the user that a job number is already created if they
> enter a duplicate number in the form that is already held in another
> table, so it will display a message box telling them this, thanks
> *** Sent via Developersdex http://www.examnotes.net ***
>|||Why are you making your users think of unique values? Why would any user car
e
what number his job is given?
Use a column constraint and design a function that will automatically
generate unique values for the job column. You sound like a crappy ISP -
designed to serve millions of users, yet each of them must create his/her ow
n
*globally unique* username in order to create a valid account. A total waste
of time.
ML|||"Fraser" <fraser68@.tiscali.co.uk> wrote in message
news:op.sy2fmed6s8gdz1@.acer64...
Hi, I'm creating a database that needs to check a value in a text
field
called JobCreate in a form called frmJobCreated against a table called
tblJobCreated which has a whole list of job numbers in a field called
JobNo, then come back with a message telling the user if there is a
duplicate value...any help would be greatly appreciated,,thanks,
Fraser
Fraser,
Pleaes try reposting your above message in *one* of the following
newsgroups:
comp.databases.ms-access
microsoft.public.access.forms
microsoft.public.access.formscoding
Sincerely,
Chris O.

Check for Date

I want to enforce users to enter a date or leave the field null into a
varchar field.
We do not own the code to our database so I can not change the field to
a date/Time (It would violate our contract). I was thinking we could
enter a check constraint (This is OK per our contact) into the database
but I am not sure how.
THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
Thanks for any help.Hi, Watson
You can use:
a) the ISDATE() function (which accepts any date format),
b) a LIKE expression (which accepts a given pattern, but cannot easily
check if the date is valid), or
c) a combination of the above
For example:
ALTER TABLE CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (ISDATE(USER_7)<>0)
or:
ALTER TABLE CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (USER_7 LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9]
[0-9][0-9]')
or:
ALTER TABLE CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (ISDATE(USER_7)<>0
AND USER_7 LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9]
1;0-9][0-9]')
Razvan
Watson SQL wrote:
> I want to enforce users to enter a date or leave the field null into a
> varchar field.
> We do not own the code to our database so I can not change the field to
> a date/Time (It would violate our contract). I was thinking we could
> enter a check constraint (This is OK per our contact) into the database
> but I am not sure how.
> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
> Thanks for any help.|||You could have a CHECK constraint as shown below:
ALTER TABLE YourTableName ADD CONSTRAINT CheckDate CHECK (ISDATE(ColumNName)
= 1 or ColumnName IS NULL)
--
HTH,
Vyas, MVP (SQL Server)
SQL Server Articles and Code Samples @. http://vyaskn.tripod.com/
"Watson SQL" <APHILLEY@.WATSONFURNITURE.COM> wrote in message
news:1152544408.938003.176800@.h48g2000cwc.googlegroups.com...
I want to enforce users to enter a date or leave the field null into a
varchar field.
We do not own the code to our database so I can not change the field to
a date/Time (It would violate our contract). I was thinking we could
enter a check constraint (This is OK per our contact) into the database
but I am not sure how.
THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
Thanks for any help.|||>I want to enforce users to enter a date or leave the field null into a
> varchar field.

> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
Try:
ALTER TABLE dbo.CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (USER_7 IS NULL OR ISDATE(USER_7) = 1)
Hope this helps.
Dan Guzman
SQL Server MVP
"Watson SQL" <APHILLEY@.WATSONFURNITURE.COM> wrote in message
news:1152544408.938003.176800@.h48g2000cwc.googlegroups.com...
>I want to enforce users to enter a date or leave the field null into a
> varchar field.
> We do not own the code to our database so I can not change the field to
> a date/Time (It would violate our contract). I was thinking we could
> enter a check constraint (This is OK per our contact) into the database
> but I am not sure how.
> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
> Thanks for any help.
>|||ALTER TABLE CUST_ORDER_LINE ADD CONSTRAINT constraintname CHECK(ISDATE(USER_
7))
No need to explicitly allow NULL. If a CHECK constraint evaluate to TRUE or
UNK, the modification is
allowed.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Watson SQL" <APHILLEY@.WATSONFURNITURE.COM> wrote in message
news:1152544408.938003.176800@.h48g2000cwc.googlegroups.com...
>I want to enforce users to enter a date or leave the field null into a
> varchar field.
> We do not own the code to our database so I can not change the field to
> a date/Time (It would violate our contract). I was thinking we could
> enter a check constraint (This is OK per our contact) into the database
> but I am not sure how.
> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
> Thanks for any help.
>

Check for Date

I want to enforce users to enter a date or leave the field null into a
varchar field.
We do not own the code to our database so I can not change the field to
a date/Time (It would violate our contract). I was thinking we could
enter a check constraint (This is OK per our contact) into the database
but I am not sure how.
THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
Thanks for any help.Hi, Watson
You can use:
a) the ISDATE() function (which accepts any date format),
b) a LIKE expression (which accepts a given pattern, but cannot easily
check if the date is valid), or
c) a combination of the above
For example:
ALTER TABLE CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (ISDATE(USER_7)<>0)
or:
ALTER TABLE CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (USER_7 LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]')
or:
ALTER TABLE CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (ISDATE(USER_7)<>0
AND USER_7 LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]')
Razvan
Watson SQL wrote:
> I want to enforce users to enter a date or leave the field null into a
> varchar field.
> We do not own the code to our database so I can not change the field to
> a date/Time (It would violate our contract). I was thinking we could
> enter a check constraint (This is OK per our contact) into the database
> but I am not sure how.
> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
> Thanks for any help.|||You could have a CHECK constraint as shown below:
ALTER TABLE YourTableName ADD CONSTRAINT CheckDate CHECK (ISDATE(ColumNName)
= 1 or ColumnName IS NULL)
--
HTH,
Vyas, MVP (SQL Server)
SQL Server Articles and Code Samples @. http://vyaskn.tripod.com/
"Watson SQL" <APHILLEY@.WATSONFURNITURE.COM> wrote in message
news:1152544408.938003.176800@.h48g2000cwc.googlegroups.com...
I want to enforce users to enter a date or leave the field null into a
varchar field.
We do not own the code to our database so I can not change the field to
a date/Time (It would violate our contract). I was thinking we could
enter a check constraint (This is OK per our contact) into the database
but I am not sure how.
THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
Thanks for any help.|||>I want to enforce users to enter a date or leave the field null into a
> varchar field.
> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
Try:
ALTER TABLE dbo.CUST_ORDER_LINE
ADD CONSTRAINT CK_CUST_ORDER_LINE_USER_7
CHECK (USER_7 IS NULL OR ISDATE(USER_7) = 1)
--
Hope this helps.
Dan Guzman
SQL Server MVP
"Watson SQL" <APHILLEY@.WATSONFURNITURE.COM> wrote in message
news:1152544408.938003.176800@.h48g2000cwc.googlegroups.com...
>I want to enforce users to enter a date or leave the field null into a
> varchar field.
> We do not own the code to our database so I can not change the field to
> a date/Time (It would violate our contract). I was thinking we could
> enter a check constraint (This is OK per our contact) into the database
> but I am not sure how.
> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
> Thanks for any help.
>|||ALTER TABLE CUST_ORDER_LINE ADD CONSTRAINT constraintname CHECK(ISDATE(USER_7))
No need to explicitly allow NULL. If a CHECK constraint evaluate to TRUE or UNK, the modification is
allowed.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Watson SQL" <APHILLEY@.WATSONFURNITURE.COM> wrote in message
news:1152544408.938003.176800@.h48g2000cwc.googlegroups.com...
>I want to enforce users to enter a date or leave the field null into a
> varchar field.
> We do not own the code to our database so I can not change the field to
> a date/Time (It would violate our contract). I was thinking we could
> enter a check constraint (This is OK per our contact) into the database
> but I am not sure how.
> THE TABLE IS CUST_ORDER_LINE AND THE FIELD IS USER_7.
> Thanks for any help.
>

check field

Hi, how to find out what table, field contain "mysearchtext" in side? Thanks
a lot.Check out the INFORMATION_SCHEMA system views for more info, but here's
something you can use fight now:
select INFORMATION_SCHEMA.[COLUMNS].TABLE_NAME
from INFORMATION_SCHEMA.[COLUMNS]
where (INFORMATION_SCHEMA.[COLUMNS].COLUMN_NAME = 'mysearchtext')
ML
http://milambda.blogspot.com/|||"js" <js@.someone.com> wrote in message
news:eLWFGf1TGHA.2656@.TK2MSFTNGP10.phx.gbl...
> Hi, how to find out what table, field contain "mysearchtext" in side?
> Thanks a lot.
You want to search through all tables and columns?
A combination of the undocumented stored procedure "sp_MSforeachtable",
this statement: select column_name from INFORMATION_SCHEMA.COLUMNS where
table_name = 'tableName'
a cursor,
dynamic SQL
and: select ... from tableName where columnName like '%mysearchtext%'|||Thanks ML,
How about search field content? hwo to do that?
"ML" <ML@.discussions.microsoft.com> wrote in message
news:C744B478-EE78-4378-9528-13106F88443C@.microsoft.com...
> Check out the INFORMATION_SCHEMA system views for more info, but here's
> something you can use fight now:
> select INFORMATION_SCHEMA.[COLUMNS].TABLE_NAME
> from INFORMATION_SCHEMA.[COLUMNS]
> where (INFORMATION_SCHEMA.[COLUMNS].COLUMN_NAME = 'mysearchtext')
>
> ML
> --
> http://milambda.blogspot.com/

Sunday, March 11, 2012

check data type and maximum length of a field

Hi All,

Is there a way to check the data type and the maximum length of a field?

Look at the INFORMATION_SCHEMA.COLUMN view, it contains the DATA_TYPE as well as either the precision / scale or the maximum allowed characters / bytes per type (where it can be defined manually like VARCHAR)

Jens K. Suessmeyer

http://www.sqlserver2005.de

Check Data Before Update

Hello Everybody!

I have a POLINE table on a SQL Server 2000 DB. Before I update the
record I need to check that either field, STORELOC or WONUM has data
on it. If both fields are NULL I would like to send a message letting
the user know that either fields needs data before they can save the
record. If any of the fields have data then, it is OK to save the
record.

Could you please let me know how to accomplish this? An example will
be really helpful, I can do this in Access but I do not know how to do
it in SQLServer. I was thinking using trigger but there are not really
good examples.

Thanks in Advance!

Martin[posted and mailed, please reply in news]

Martin (martin.wunder@.wsidc.com) writes:
> I have a POLINE table on a SQL Server 2000 DB. Before I update the
> record I need to check that either field, STORELOC or WONUM has data
> on it. If both fields are NULL I would like to send a message letting
> the user know that either fields needs data before they can save the
> record. If any of the fields have data then, it is OK to save the
> record.
> Could you please let me know how to accomplish this? An example will
> be really helpful, I can do this in Access but I do not know how to do
> it in SQLServer. I was thinking using trigger but there are not really
> good examples.

The answer is that you don't do this in SQL Server.

No, get me right. You can certainly have a check for this in SQL Server:

create table POLINE (...
STORELOC some_type not null,
WONUM other_type not null,
...
constraint POLINE_CHK_STORELOC_WONUM
check (STORELOC is not null or WONUM is not
null)

This table constraint will cause SQL Server to flatly accept any rows
where both columns are NULL. If exactly one should be non-NULL the
check should read:

STORELOCK is not null and WONUM is null or
STORELOCK is null and WONUM is not null

However, this does not really meet your requirements, because the
message will not be useful to the user. To this end, you need to
do the check in the client.

There is an important difference between Access and SQL Server. Access
is both database and GUI in one, but SQL Server is only the server
side, and requires a client on the other end. (Which could be Access.)

Still constraints like these are very useful, because they can cover
up for tests that the GUI programmer failed to include, and protect
the integirty of the data.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Check Constraint help,, Alpha and Numeric

Hey there, In SQL server 2000, I need to create a constraint on one of
the columns that the field enterd must be 2 alpha charactors and the
last 3 must be numeric.
soo, for example
aa123
thanx in advanceUse something like this:
ALTER TABLE TableName ADD CONSTRAINT ConstraintName
CHECK (ColumnName LIKE '[A-Z][A-Z][0-9][0-9][0-9]')
Razvan
Bonzol wrote:
> Hey there, In SQL server 2000, I need to create a constraint on one of
> the columns that the field enterd must be 2 alpha charactors and the
> last 3 must be numeric.
> soo, for example
> aa123
> thanx in advance|||Thanx, but where would I actually put this? atm im trying through right
clicking on the column and creatinng a constraint|||You can execute the above statement in a Management Studio query window
(or in Query Analyzer if you are using SQL Server 2000).
If you want to do this using the graphical interface (in Management
Studio), you should go to the Constraints node (not the Columns node),
right click and choose "New Constraint..."; in the "Expression", type:
ColumnName LIKE '[A-Z][A-Z][0-9][0-9][0-9]'
(of course, replace ColumnName with the name of your column)
Razvan

Check Constraint help,, Alpha and Numeric

Hey there, In SQL server 2000, I need to create a constraint on one of
the columns that the field enterd must be 2 alpha charactors and the
last 3 must be numeric.
soo, for example
aa123
thanx in advanceUse something like this:
ALTER TABLE TableName ADD CONSTRAINT ConstraintName
CHECK (ColumnName LIKE '[A-Z][A-Z][0-9][0-9][0-9]')
Razvan
Bonzol wrote:
> Hey there, In SQL server 2000, I need to create a constraint on one of
> the columns that the field enterd must be 2 alpha charactors and the
> last 3 must be numeric.
> soo, for example
> aa123
> thanx in advance|||Thanx, but where would I actually put this? atm im trying through right
clicking on the column and creatinng a constraint|||You can execute the above statement in a Management Studio query window
(or in Query Analyzer if you are using SQL Server 2000).
If you want to do this using the graphical interface (in Management
Studio), you should go to the Constraints node (not the Columns node),
right click and choose "New Constraint..."; in the "Expression", type:
ColumnName LIKE '[A-Z][A-Z][0-9][0-9][0-9]'
(of course, replace ColumnName with the name of your column)
Razvan

Check Constraint Expression

I'm using SQL Server 2005 and new to it.
I'm wanting to modify a Check constraint expression to say that the field (a
description) needs to be unique. I also want it to be null, but figure I ca
n
allow nulls or not within the field definition. Can I specify that in the
constraint as well?
Mainly, I need to be able to say that the field is unique, and since it's a
description.
How do I do this?I tried the following, but this didn't work. I was able to enter duplicate
descriptions.
([OrderTypeDescription] IS NOT NULL AND
[OrderTypeDescription] NOT IN (SELECT OrderTypeDescription FROM T_OrderType))
"HockeyFan" wrote:

> I'm using SQL Server 2005 and new to it.
> I'm wanting to modify a Check constraint expression to say that the field
(a
> description) needs to be unique. I also want it to be null, but figure I
can
> allow nulls or not within the field definition. Can I specify that in the
> constraint as well?
> Mainly, I need to be able to say that the field is unique, and since it's
a
> description.
> How do I do this?
>|||You don't want a CHECK constraint. Drop any existing CHECK constraint.
Make the column NOT NULL and add a UNIQUE constraint.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"HockeyFan" <HockeyFan@.discussions.microsoft.com> wrote in message
news:D6DEF6E6-3B74-47F9-92DE-9688198EE8EF@.microsoft.com...
I'm using SQL Server 2005 and new to it.
I'm wanting to modify a Check constraint expression to say that the field (a
description) needs to be unique. I also want it to be null, but figure I
can
allow nulls or not within the field definition. Can I specify that in the
constraint as well?
Mainly, I need to be able to say that the field is unique, and since it's a
description.
How do I do this?|||Where do I do that from within the SQL Server Management Studio?
"Tom Moreau" wrote:

> You don't want a CHECK constraint. Drop any existing CHECK constraint.
> Make the column NOT NULL and add a UNIQUE constraint.
> --
> Tom
> ----
> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
> SQL Server MVP
> Columnist, SQL Server Professional
> Toronto, ON Canada
> www.pinpub.com
> ..
> "HockeyFan" <HockeyFan@.discussions.microsoft.com> wrote in message
> news:D6DEF6E6-3B74-47F9-92DE-9688198EE8EF@.microsoft.com...
> I'm using SQL Server 2005 and new to it.
> I'm wanting to modify a Check constraint expression to say that the field
(a
> description) needs to be unique. I also want it to be null, but figure I
> can
> allow nulls or not within the field definition. Can I specify that in the
> constraint as well?
> Mainly, I need to be able to say that the field is unique, and since it's
a
> description.
> How do I do this?
>|||I'd just do it in a query:
alter table MyTable
drop
constraint MyConstraint
go
alter table MyTable
alter column
MyCol int not null
go
alter table MyTable
add
constraint MyConstraint unique (MyCol)
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"HockeyFan" <HockeyFan@.discussions.microsoft.com> wrote in message
news:D3170FBC-98AB-4FC5-9D20-4B697F698781@.microsoft.com...
Where do I do that from within the SQL Server Management Studio?
"Tom Moreau" wrote:

> You don't want a CHECK constraint. Drop any existing CHECK constraint.
> Make the column NOT NULL and add a UNIQUE constraint.
> --
> Tom
> ----
> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
> SQL Server MVP
> Columnist, SQL Server Professional
> Toronto, ON Canada
> www.pinpub.com
> ..
> "HockeyFan" <HockeyFan@.discussions.microsoft.com> wrote in message
> news:D6DEF6E6-3B74-47F9-92DE-9688198EE8EF@.microsoft.com...
> I'm using SQL Server 2005 and new to it.
> I'm wanting to modify a Check constraint expression to say that the field
> (a
> description) needs to be unique. I also want it to be null, but figure I
> can
> allow nulls or not within the field definition. Can I specify that in the
> constraint as well?
> Mainly, I need to be able to say that the field is unique, and since it's
> a
> description.
> How do I do this?
>|||>I'm using SQL Server 2005 and new to it.
>I'm wanting to modify a Check constraint expression to say that the field (
a
>description) needs to be unique. I also want it to be null, but figure I c
an
>allow nulls or not within the field definition. Can I specify that in the
>constraint as well?
If I understand you, you want to allow the column to be NULL, but if
it is NOT null you want it to be UNIQUE. Is that correct?
If so, the next question is whether only one row can be NULL, or any
number of rows can be NULL. If only a single NULL row is allowed then
Tom's approach of adding a UNIQUE contraint will work fine. However,
if multiple NULL rows is allowed UNIQUE will fail on the second
occurance.
If what you need is multiple NULLs but unique non-NULL values, then we
just need a small adjustment to the code you posted.
(OrderTypeDescription IS NULL OR
OrderTypeDescription NOT IN
(SELECT OrderTypeDescription FROM T_OrderType))
Roy|||The proposed solution will allow a single null value.
I'd rather create an indexed view for that constraint (providing that the
description column allows nulls):
create view dbo.UniqueDescription
with schemabinding
as
select <column list>
,<description column>
from <table>
where (<description column> is not null)
go
create unique clustered index <index name>
on dbo.UniqueDescription
(
<clustered index candidate>
)
go
create unique nonclustered index <index name>
on dbo.UniqueDescription
(
<description column>
)
go
ML
http://milambda.blogspot.com/

Thursday, March 8, 2012

Check Constraint

I'm having a little trouble enforcing a unique record rule. The problem is
a
DateTime field is used in the unique value, but I only need to the DatePart
(not
the time), otherwise I would use a standard unique constraint.
I need the combination of ResID,RxDayID,RxTimeID, and Just The Date of
DispDateTime to be unique.
The following works for inserts but not updates if a record already exists.
It
does work if there are 2 matching records for an update. I'd rather have th
e
back-end enforce the rules, but if I must I'll build it into the application
.
Is there a function or a method I'm over-looking?
ALTER TABLE [dbo].[ResRxDispensed] ADD
CONSTRAINT [CK_ResRxDispensed_Unique]
CHECK ([dbo].[DispRecordUnique_FN](
[ResID],
[RxDayID],
[RxDoseTimeID],
[DispDateTime]) = 'Y')
Create Function [dbo].[DispRecordUnique_FN](
@.ResID Int,
@.RxDayID Int,
@.RxTimeID Int,
@.ADate DateTime)
Returns VarChar(1)
Begin
Declare @.TheDate DateTime, @.Rtn Varchar(1),@.Cnt Int
Set @.TheDate = Cast(Cast(@.ADate as Char(11)) As DateTime)
Set @.Rtn = 'N'
Select @.Cnt = Count(*)
From ResRxDispensed
Where ResID = @.ResID
And RxDayID = @.RxDayID
And RxDoseTimeID = @.RxTimeID
And (DispDateTime >= @.TheDate And DispDateTime <= (@.TheDate+1))
If (@.Cnt <= 1)
Begin
Set @.Rtn = 'Y'
End
Return @.Rtn
End
TIA,
-Steve-You've overcomplicated the solution IMHO:
1) create a computed column:
alter table dbo.ResRxDispensed
add DispDate as convert(char(8), DispDateTime, 112)
go
2) create the unique constraint:
alter table dbo.ResRxDispensed
add constraint <constraint name>
unique (ResID, RxDayID, RxTimeID, DispDate)
go
If this does not help, please post proper DDL and maybe sample data.
ML
http://milambda.blogspot.com/|||Experiment to see if the year(), month(), day() or datediff() functions
would work here.
"Steve Zimmelman" <skz@.charter.nospam.net> wrote in message
news:%23kFjHVZWGHA.2180@.TK2MSFTNGP02.phx.gbl...
> I'm having a little trouble enforcing a unique record rule. The problem
> is a DateTime field is used in the unique value, but I only need to the
> DatePart (not the time), otherwise I would use a standard unique
> constraint.
> I need the combination of ResID,RxDayID,RxTimeID, and Just The Date of
> DispDateTime to be unique.
> The following works for inserts but not updates if a record already
> exists. It does work if there are 2 matching records for an update. I'd
> rather have the back-end enforce the rules, but if I must I'll build it
> into the application. Is there a function or a method I'm over-looking?
> ALTER TABLE [dbo].[ResRxDispensed] ADD
> CONSTRAINT [CK_ResRxDispensed_Unique]
> CHECK ([dbo].[DispRecordUnique_FN](
> [ResID],
> [RxDayID],
> [RxDoseTimeID],
> [DispDateTime]) = 'Y')
>
> Create Function [dbo].[DispRecordUnique_FN](
> @.ResID Int,
> @.RxDayID Int,
> @.RxTimeID Int,
> @.ADate DateTime)
> Returns VarChar(1)
> Begin
> Declare @.TheDate DateTime, @.Rtn Varchar(1),@.Cnt Int
> Set @.TheDate = Cast(Cast(@.ADate as Char(11)) As DateTime)
> Set @.Rtn = 'N'
> Select @.Cnt = Count(*)
> From ResRxDispensed
> Where ResID = @.ResID
> And RxDayID = @.RxDayID
> And RxDoseTimeID = @.RxTimeID
> And (DispDateTime >= @.TheDate And DispDateTime <= (@.TheDate+1))
> If (@.Cnt <= 1)
> Begin
> Set @.Rtn = 'Y'
> End
> Return @.Rtn
> End
> TIA,
> -Steve-
>|||Thanks.
I tried your suggestion but it apparently doesn't work when you use a comput
ed
column in a constraint. When I attempt to add a record I get the errror:
[INSERT failed because the following SET options have incorrect settings:
'ARITHABORT']
Using SET ARITHABORT ON before the insert/update works, but it seems it must
be
issued before each update/insert statement.

> If this does not help, please post proper DDL and maybe sample data.
CREATE TABLE [dbo].[ResRxDispensed] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[ResID] [int] NULL ,
[ResRxID] [int] NULL ,
[RxDayID] [int] NULL ,
[RxDoseTimeID] [int] NULL ,
[DispDateTime] [datetime] NULL ,
[Created] [datetime] NULL ,
[StaffID] [int] NULL ,
[DispDate] AS (convert(char(8),[DispDateTime],112))
) ON [PRIMARY]
Insert Into ResRxDispensed
([ResID],[ResRxID],[RxDayID],[RxDoseTime
ID],[DispDateTime])
Values
(1,1,1,1,{ts '2006-04-06 09:30:00'}) ;
The insert should fail if another record has
ResID = 1
RxDayID = 1
RxDoseTimeID = 1
DispDateTime = 2006-04-06 (with any time factor)
Updates should also fail if the update changes the record to match another
record with the criteria.
-Steve-|||
"JT" <someone@.microsoft.com> wrote in message
news:%23sosFSaWGHA.4424@.TK2MSFTNGP05.phx.gbl...
> Experiment to see if the year(), month(), day() or datediff() functions wo
uld
> work here.
I'm not sure I understand. Experiment how? The function
DispRecordUnique_FN()works, but using it in a Check constraint only works on
Inserts, not updates.
-Steve-|||This worked fine for me on SQL 2000.
CREATE TABLE [dbo].[TestTable] (
[ResID] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[RxDayID] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[RxDoseTimeID] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[DispDateTime] [datetime] NOT NULL ,
[OtherData] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[DispDate] AS (convert(char(8),[DispDateTime],112))
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TestTable] ADD
CONSTRAINT [IX_TestTable] UNIQUE NONCLUSTERED
(
[ResID],
[RxDoseTimeID],
[RxDayID],
[DispDate]
) ON [PRIMARY]
GO
"Steve Zimmelman" <skz@.charter.nospam.net> wrote in message
news:ep7wCVaWGHA.1220@.TK2MSFTNGP02.phx.gbl...
> Thanks.
> I tried your suggestion but it apparently doesn't work when you use a
computed
> column in a constraint. When I attempt to add a record I get the errror:
> [INSERT failed because the following SET options have incorrect settings:
> 'ARITHABORT']
> Using SET ARITHABORT ON before the insert/update works, but it seems it
must be
> issued before each update/insert statement.
>
> CREATE TABLE [dbo].[ResRxDispensed] (
> [ID] [int] IDENTITY (1, 1) NOT NULL ,
> [ResID] [int] NULL ,
> [ResRxID] [int] NULL ,
> [RxDayID] [int] NULL ,
> [RxDoseTimeID] [int] NULL ,
> [DispDateTime] [datetime] NULL ,
> [Created] [datetime] NULL ,
> [StaffID] [int] NULL ,
> [DispDate] AS (convert(char(8),[DispDateTime],112))
> ) ON [PRIMARY]
>
> Insert Into ResRxDispensed
> ([ResID],[ResRxID],[RxDayID],[RxDoseTime
ID],[DispDateTime])
> Values
> (1,1,1,1,{ts '2006-04-06 09:30:00'}) ;
> The insert should fail if another record has
> ResID = 1
> RxDayID = 1
> RxDoseTimeID = 1
> DispDateTime = 2006-04-06 (with any time factor)
> Updates should also fail if the update changes the record to match another
> record with the criteria.
> -Steve-
>
>|||> This worked fine for me on SQL 2000.
Hi Jim,
Thanks. I'm using SQL 2000, but I'm still getting the same error.
Here's the scripts for creating everything I'm using.
CREATE TABLE [dbo].[ResRxDispensed] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[ResID] [int] NULL ,
[ResRxID] [int] NULL ,
[RxDayID] [int] NULL ,
[RxDoseTimeID] [int] NULL ,
[DispDateTime] [datetime] NOT NULL ,
[Created] [datetime] NULL ,
[StaffID] [int] NULL ,
[DispDate] AS (convert(char(8),[DispDateTime],112))
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ResRxDispensed] WITH NOCHECK ADD
CONSTRAINT [PK_ResRxDispensed] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ResRxDispensed] ADD
CONSTRAINT [DF_ResRxDispensed_DispDateTime] DEFAULT (getdate()) FOR
[DispDateTime],
CONSTRAINT [DF_ResRxDispensed_Created] DEFAULT (getdate()) FOR [Created],
CONSTRAINT [IX_ResRxDispensed] UNIQUE NONCLUSTERED
(
[ResID],
[RxDayID],
[RxDoseTimeID],
[DispDate]
) ON [PRIMARY]
GO
CREATE INDEX [ResRxDispensed_ResID] ON [dbo].[ResRxDispensed]([ResID]) ON
[PRIMARY]
GO
CREATE INDEX [ResRxDispensed_ResRxID] ON [dbo].[ResRxDispensed]([ResRxID]) ON
[PRIMARY]
GO
CREATE INDEX [ResRxDispensed_RxDayID] ON [dbo].[ResRxDispensed]([RxDayID]) ON
[PRIMARY]
GO
CREATE INDEX [ResRxDispensed_RxDoseTimeID] ON
[dbo].[ResRxDispensed]([RxDoseTimeID]) ON [PRIMARY]
GO
-Steve-|||Is there a reason why you can't add this SET option to your stored procedure
s?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Steve Zimmelman" <skz@.charter.nospam.net> wrote in message
news:%23Set$paWGHA.2080@.TK2MSFTNGP05.phx.gbl...
> Hi Jim,
> Thanks. I'm using SQL 2000, but I'm still getting the same error.
> Here's the scripts for creating everything I'm using.
> CREATE TABLE [dbo].[ResRxDispensed] (
> [ID] [int] IDENTITY (1, 1) NOT NULL ,
> [ResID] [int] NULL ,
> [ResRxID] [int] NULL ,
> [RxDayID] [int] NULL ,
> [RxDoseTimeID] [int] NULL ,
> [DispDateTime] [datetime] NOT NULL ,
> [Created] [datetime] NULL ,
> [StaffID] [int] NULL ,
> [DispDate] AS (convert(char(8),[DispDateTime],112))
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[ResRxDispensed] WITH NOCHECK ADD
> CONSTRAINT [PK_ResRxDispensed] PRIMARY KEY CLUSTERED
> (
> [ID]
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[ResRxDispensed] ADD
> CONSTRAINT [DF_ResRxDispensed_DispDateTime] DEFAULT (getdate()) FOR [DispDateTime],
> CONSTRAINT [DF_ResRxDispensed_Created] DEFAULT (getdate()) FOR [Created],
> CONSTRAINT [IX_ResRxDispensed] UNIQUE NONCLUSTERED
> (
> [ResID],
> [RxDayID],
> [RxDoseTimeID],
> [DispDate]
> ) ON [PRIMARY]
> GO
> CREATE INDEX [ResRxDispensed_ResID] ON [dbo].[ResRxDispensed]([ResID]) ON [PRIMARY]
> GO
> CREATE INDEX [ResRxDispensed_ResRxID] ON [dbo].[ResRxDispensed]([ResRxID]) ON [PRIMARY]
> GO
> CREATE INDEX [ResRxDispensed_RxDayID] ON [dbo].[ResRxDispensed]([RxDayID]) ON [PRIMARY]
> GO
> CREATE INDEX [ResRxDispensed_RxDoseTimeID] ON [dbo].[ResRxDispensed]([RxDoseTimeID]) ON [PRIMARY]
> GO
>
> -Steve-
>|||"Tibor Karaszi" wrote
> Is there a reason why you can't add this SET option to your stored procedures?[/co
lor]
I suppose not. I just wanted something that didn't require such special
handling for updates in case I needed to do some manual repair/entry outside
of
the application.
-Steve-|||"Tibor Karaszi" wrote:
> Is there a reason why you can't add this SET option to your stored procedures?[/co
lor]
This procedure, when used, produces the same error.
[INSERT failed because the following SET options have incorrect settings:
'ARITHABORT']
I'm at a loss how to proceed...
-Steve-
Exec NewResRxDispensed_SP 1,1,1,1,{ts '2006-05-13 09:30:00'},24
Create Procedure [dbo].[NewResRxDispensed_SP]
@.ResID int,
@.ResRxID int,
@.RxDayID int,
@.RxDoseTimeID int,
@.DispDateTime datetime,
@.StaffID int
As
SET ARITHABORT ON
Insert Into [ResRxDispensed]
([ResID],
[ResRxID],
[RxDayID],
[RxDoseTimeID],
[DispDateTime],
[StaffID])
Values
(@.ResID,
@.ResRxID,
@.RxDayID,
@.RxDoseTimeID,
@.DispDateTime,
@.StaffID)
/*** Return New Int ID [ID] ***/
Select SCOPE_IDENTITY() As NewID

Check constraint

I am new to SQL Server, so I'm not quite sure how to use this feature. I need to limit a field to only accept a set of three values: H, Q, and C. I know how to do this in a native Access table. I'm not quite sure how to do this in SQL Server. I assum
e this is what a check constraint is, but I don't know how to set one up or where to implement it.
Any suggestions would be greatly appreciated,
Crystal
Yep, it's a check constraint:
create table MyTable
(
PK int primary key
, MyCol char (1) not null constraint CK_MyTable (MyCol in ('H', 'Q',
'C'))
)
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
..
"Crystal" <anonymous@.discussions.microsoft.com> wrote in message
news:BC380E12-BD25-4308-8860-08617207DEE4@.microsoft.com...
I am new to SQL Server, so I'm not quite sure how to use this feature. I
need to limit a field to only accept a set of three values: H, Q, and C. I
know how to do this in a native Access table. I'm not quite sure how to do
this in SQL Server. I assume this is what a check constraint is, but I
don't know how to set one up or where to implement it.
Any suggestions would be greatly appreciated,
Crystal
|||Try this -
create table test (
iintidentity
, jchar(1)
check (j in ('H', 'Q', 'C'))
)
|||Ok. This is what is going to make me look like a dork. . .
Now that I have the syntax. . . where do I put it to create the check constraint?
Crystal
|||The syntax I showed you is to create the constraint at the time you create
the table. However, if the table already exists, you can do an ALTER TABLE:
alter table MyTable
add
constraint CK_MyTable (MyCol in ('H', 'Q', 'C'))
go
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Crystal" <anonymous@.discussions.microsoft.com> wrote in message
news:CFC4AF0F-052F-442A-8037-307EC3A3D437@.microsoft.com...
Ok. This is what is going to make me look like a dork. . .
Now that I have the syntax. . . where do I put it to create the check
constraint?
Crystal

Check constraint

I am new to SQL Server, so I'm not quite sure how to use this feature. I need to limit a field to only accept a set of three values: H, Q, and C. I know how to do this in a native Access table. I'm not quite sure how to do this in SQL Server. I assume this is what a check constraint is, but I don't know how to set one up or where to implement it
Any suggestions would be greatly appreciated
CrystalThis is a multi-part message in MIME format.
--=_NextPart_000_012E_01C42099.51AAF520
Content-Type: text/plain;
charset="Utf-8"
Content-Transfer-Encoding: 7bit
Yep, it's a check constraint:
create table MyTable
(
PK int primary key
, MyCol char (1) not null constraint CK_MyTable (MyCol in ('H', 'Q',
'C'))
)
--
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
.
"Crystal" <anonymous@.discussions.microsoft.com> wrote in message
news:BC380E12-BD25-4308-8860-08617207DEE4@.microsoft.com...
I am new to SQL Server, so I'm not quite sure how to use this feature. I
need to limit a field to only accept a set of three values: H, Q, and C. I
know how to do this in a native Access table. I'm not quite sure how to do
this in SQL Server. I assume this is what a check constraint is, but I
don't know how to set one up or where to implement it.
Any suggestions would be greatly appreciated,
Crystal
--=_NextPart_000_012E_01C42099.51AAF520
Content-Type: text/html;
charset="Utf-8"
Content-Transfer-Encoding: quoted-printable
=EF=BB=BF<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Yep, it's a check =constraint:
create table =MyTable
(
PK int primary =key
, =MyCol char (1) not null constraint CK_MyTable (MyCol in =('H', 'Q', 'C'))
)
-- Tom
----Thomas A. =Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql.
"Crystal" wrote in message news:BC3=80E12-BD25-4308-8860-08617207DEE4@.microsoft.com...I am new to SQL Server, so I'm not quite sure how to use this =feature. I need to limit a field to only accept a set of three values: H, Q, =and C. I know how to do this in a native Access table. I'm not =quite sure how to do this in SQL Server. I assume this is what a check constraint is, but I don't know how to set one up or where to implement it.Any suggestions would be greatly appreciated,Crystal

--=_NextPart_000_012E_01C42099.51AAF520--|||Ok. This is what is going to make me look like a dork. .
Now that I have the syntax. . . where do I put it to create the check constraint
Crystal|||This is a multi-part message in MIME format.
--=_NextPart_000_0086_01C42136.B95D8140
Content-Type: text/plain;
charset="Utf-8"
Content-Transfer-Encoding: 7bit
The syntax I showed you is to create the constraint at the time you create
the table. However, if the table already exists, you can do an ALTER TABLE:
alter table MyTable
add
constraint CK_MyTable (MyCol in ('H', 'Q', 'C'))
go
--
Tom
---
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Crystal" <anonymous@.discussions.microsoft.com> wrote in message
news:CFC4AF0F-052F-442A-8037-307EC3A3D437@.microsoft.com...
Ok. This is what is going to make me look like a dork. . .
Now that I have the syntax. . . where do I put it to create the check
constraint?
Crystal
--=_NextPart_000_0086_01C42136.B95D8140
Content-Type: text/html;
charset="Utf-8"
Content-Transfer-Encoding: quoted-printable
=EF=BB=BF<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

The syntax I showed you is to create =the constraint at the time you create the table. However, if the table =already exists, you can do an ALTER TABLE:
alter table =MyTable
add
=constraint CK_MyTable (MyCol in ('H', 'Q', 'C'))
go
-- Tom
---T=homas A. Moreau, BSc, PhD, MCSE, MCDBASQL Server MVPColumnist, SQL =Server ProfessionalToronto, ON Canadahttp://www.pinnaclepublishing.com/sql">www.pinnaclepublishing.com=/sql
"Crystal" wrote in message news:CFC=4AF0F-052F-442A-8037-307EC3A3D437@.microsoft.com...Ok. This is what is going to make me look like a dork. . .Now that I =have the syntax. . . where do I put it to create the check constraint?Crystal

--=_NextPart_000_0086_01C42136.B95D8140--

Check Constraint

I have an existing table with field ZIPCODE defined as VARCHAR(5).
I want to add a check constraint to allow only number from 0 to 9.

This is what I did but it gave me error:

alter table test
with check
add constraint ck_test
check (zip between '0' and '9')

error:

ALTER TABLE statement conflicted with COLUMN CHECK constraint 'ck_test'.
The conflict occurred in database 'lahdProperty', table 'test', column 'Zip'.

What did I do wrong. Thanks for your help.Don't have access to bol and my machine...I'll figure it out tomorrow, unless you get it tonight

BUT

Look at LIKE [0-9][0-9][0-9][0-9][0-9]|||I guess u r trying to check a single digit as zip.
existing data in the table conflicts with the constraint u r trying to add
so try to alter table with nocheck option.
or else drop the column and add it in which ever way u want.
------------------------
alter table test
with nocheck
add constraint ck_test
check (zip between '0' and '9')
------------------------

Originally posted by ttkh
I have an existing table with field ZIPCODE defined as VARCHAR(5).
I want to add a check constraint to allow only number from 0 to 9.

This is what I did but it gave me error:

alter table test
with check
add constraint ck_test
check (zip between '0' and '9')

error:

ALTER TABLE statement conflicted with COLUMN CHECK constraint 'ck_test'.
The conflict occurred in database 'lahdProperty', table 'test', column 'Zip'.

What did I do wrong. Thanks for your help.

Check Constraint

In our database we have an indexed field that is using unique values, so in the index we turned on the unique property. Now with some changes we made in the application this value can be Null (could not be Null in the past). When we have more as 1 value having value Null we get an exception of unique key violation.

Therefor we want to make an check constraint the checks if the value allready exists when the value is not Null.

Is this possible and how can it be done?

You're going to need to use a trigger to check the values in the way you described.|||Hi,

I'm getting the same error.
When I try to add a new user I receive this errror:

ystem.Data.ConstraintException: Column 'User ID' is constrained to be unique. Value '{37525b24-d982-470d-9d1c-e3b3c7536958}' is already present.
at System.Data.UniqueConstraint.CheckConstraint(DataRow row, DataRowAction action)
at System.Data.DataTable.RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction, Boolean fireEvent)

Unfortunately I have only one entry on my db with this User ID value. Moreover I have try to delete all my users with BU.
Can anybody help me?

Thanks a lot,

F.T