CREATE TABLE, CHECK possible text values

梦想的初衷 提交于 2021-01-05 13:19:51

问题


I'm using MS Access 2010 and I'm trying to create tables using SQL. I would like to put in some check constraints but I'm having some troubles:

CREATE TABLE Test (
tester Text CHECK (tester IN ('ABC', 'BCD', 'CDE'))
);

I'm getting a syntax error,

Any suggestions?

Thank you!

EDIT: Sorry if I wasn't clear. What I would like actually is to CHECK that tester is either "ABC", "BCD" or "CDE" those are the only values he can have.

EDIT2: I tried something else:

CREATE TABLE Test (
tester Text NOT NULL,
CONSTRAINT m_pk PRIMARY KEY(tester),
CONSTRAINT check_tester CHECK (DATALENGTH(tester) > 2)
);

and I also get a syntax error. Is there something I'm really not understanding with checking Text values? I can't possibly see where either of these is wrong.


回答1:


Beginning with Jet 4, CHECK contraints are supported for Access DDL executed from ADO, but not from DAO.

You can execute a single DDL statement which creates the table Test with your constraint. You don't need to execute one statement to create the table and then another to add the constraint.

CREATE TABLE Test
    (
        tester TEXT(255),
        CONSTRAINT ABC_or_BCD_or_CDE CHECK
            (
                tester IN ('ABC', 'BCD', 'CDE')
            )
    );

I formatted it that way to make it easier to examine the pieces. You could use this VBA to execute the statement:

strSql = "CREATE TABLE Test ( tester Text(255)," & vbCrLf & _
    "CONSTRAINT ABC_or_BCD_or_CDE" & vbCrLf & _
    "CHECK ( tester IN ('ABC', 'BCD', 'CDE')));"
Debug.Print strSql
CurrentProject.Connection.Execute strSql

Notes:

  • CurrentProject.Connection is an ADO object, so its .Execute method succeeds. The same statement with CurrentDb.Execute (a DAO method) would fail.
  • With ADO, declaring a field as TEXT without including a length (tester TEXT instead of tester TEXT(255)) will give you a memo field.



回答2:


You will need to run against a connection:

ssql = "CREATE TABLE Test (tester Text)"
CurrentProject.Connection.Execute ssql

ssql = "ALTER TABLE test ADD CONSTRAINT " _
     & "myrule CHECK (tester IN ('ABC', 'BCD', 'CDE'))"
CurrentProject.Connection.Execute ssql

Or

sSQL = "CREATE TABLE Test (tester Text, " _
     & "CONSTRAINT myrule CHECK (tester IN ('ABC', 'BCD', 'CDE')))"

Note that the name, myrule in this case, must not already exists, even for a different table.

Some notes: Is it possible to create a check constraint in access and/or DAO?




回答3:


My bad, It appears MS Access does not allow CHECK Constraints except for primary and foreign keys. My teacher taught her course with Oracle until last year and apparently did not see that this could not be done in MS Access.



来源:https://stackoverflow.com/questions/15467802/create-table-check-possible-text-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!