SQL to add column with default value - Access 2003 - sql

Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas?
This works fine
ALTER TABLE documents ADD COLUMN membersOnly NUMBER
I want this to work:
ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!

Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database.
then you can execute your query:
ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0

With ADO, you can execute a DDL statement to create a field and set its default value.
CurrentProject.Connection.Execute _
"ALTER TABLE discardme ADD COLUMN membersOnly SHORT DEFAULT 0"

How are you connecting to the database to run the update SQL? You can use the ODBC compatible mode through ADO. Without opening the database in Access.

You may find Sql Server Compatible Syntax is already turned on, so definately worth just trying to run the sql statement mentioned above (via an ADO connection from ASP) before resorting to taking the db offline. Thanks, this helped me out.

Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database.
is not found on MS Access 2010

Related

Using SSMA to convert from Access to SQL, scripting the fixes

I am using SSMA to convert from an Access db to a SQL 2019 DB.
There are some things I need to fix in the access DB so I am trying to figure out whether or not these things can be done via a query in access or you have to use the goofy UI and do everything manually.
So I had a couple of questions about queries in Microsoft Access:
Can you modify the 'required' attribute on a column within a table by using a query?
Can you configure Index (dupes) on a column by using a query?
Can you change validation rules using a query?
Can you create/delete relationships using a query?
Can you change the field length of a column by using a query?
Any examples of any of these would be helpful, when I google for ms access related things all of the content is either related to Access 2007/2010 or its very UI heavy rather than Query heavy.
I am trying to script this because I may have to do this migration several times.
Update: I was able to get most of what i needed figured out..
ALTER TABLE Users ALTER COLUMN Type CHECK(In ("I","U","") Or Is Null);
Still havent found a way to change the 'ValidationRule'.. trying to change it to
In ("I","U","") Or Is Null
Look into the Data Definition Language section of the MS Access SQL Reference, specifically the ALTER TABLE statement, which will cover the majority of your questions.
For example, in response to:
Can you change the field length of a column by using a query?
ALTER TABLE Table1 ALTER COLUMN Field1 TEXT(100)
The above will change the data type of the field Field1 within table Table1 to a text field accommodating 100 characters.

SQL Server : error validating the default for a XML column

I am trying to set the default value for a new column I just added. In properties I am trying to set 'Default Value or Binding' to a simple XML along the lines of:
<root>
<title>Welcome</title>
<body>Thank you for your time.</body>
</root>
However, when I click away, I get an error:
SQL error validating the default for column
I set this value in other numerical columns and it worked fine. What gives?
Not sure, but the visual designers in SQL Server Management Studio often don't quite work properly...
Just use a simple T-SQL statement to achieve the same thing:
ALTER TABLE dbo.YourTableName
ADD CONSTRAINT DF_YourTable_YourXmlColumn
DEFAULT '<root><title>Welcome</title><body>Thank you for your time.</body></root>'
FOR YourXmlColumn
and you're done!
(You didn't specify your table and column names - so I just made up placeholders - do replace those with your actual table and column names! Also: for the default constraint, I'd always recommend specifying an explicit name - makes it easier to disable and/or drop the constraint later, if you ever need to; my default naming convention is shown - again: adapt to your needs / likes)
It is true that knowing what TSQL command to run is advantageous in many ways but just to add an answer for SQL Server Management Studio so it is not swept under "it doesn't quite work properly", the syntax is ('[xml here]').
('<root><title>Welcome</title><body>Thank you for your time.</body></root>')

Access adding column of type decimal(number with fieldsize decimal)

In access 2007 how to add a column of type decimal to the access table using query?
In GUI i can select data type as Number and for that i can set field size as Decimal.
Now i want to do the same using query.How it can be done?
i tried running following in access query option.but didn't work
ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (10,3)
Also How can i ad column with data type Date/time and format as longtime.So please tell me how both of this can be done using query OR by using any code.
Your query looks fine.
The decimal data type isn't supported in the default Jet 4.0 mdb file. You have to use the SQL Server compatibility syntax (ANSI 92) setting to use the decimal data type in the SQL Window.
Click on the menu, Tools > Options. Click on the Tables/Query tab. Mark the check box for "This database" in the SQL Server compatibility syntax (ANSI 92) section. This mode will affect the entire db, including queries with wildcards, so you may want to try this on a copy of your db
VBA Solution
Dim db As Database
Dim t As TableDef
Dim f As Field
Dim p
Set db = CurrentDb
Set t = db.TableDefs("myTable")
Set f = t.createField("myDateField", dbDate)
Call t.Fields.Append(f)
Set p = f.CreateProperty("Format", dbText, "Long Date")
Call f.Properties.Append(p)
The office.microsoft link above has disappeared now too. Here's how to set the SQL Server Compatibility Syntax flag in Access 2007 (and maybe later - I can't check as I only have 2007):
Click the round Office button in the top left hand corner
Access Options
Object Designers
Click either of the options under SQL Server Compatible Syntax, depending on whether you want it to apply to just this database, or all future databases
If the "This database" checkbox is disabled, try closing and reopening the database, and go through these steps again without touching any other part of the database first
After this change, using legacy "DECIMAL(11,2)" SQL when creating/altering tables worked fine.

SQL statement against Access 2010 DB not working with ODBC

I'm attempting to run a simple statement against an Access DB to find records.
Data validation in the records was horrible, and I cannot sanitize it. Meaning, it must be preserved as is.
I need to be able to search against a string with white space and hyphen characters removed. The following statement will work in Access 2010 direct:
select * from dummy where Replace(Replace([data1],' ',''),'-','') = 'ABCD1234';
Running it from an ODBC connection via PHP will not. It produces the following error:
SQL error: [Microsoft][ODBC Microsoft Access Driver] Undefined function 'Replace' in expression., SQL state 37000 in SQLExecDirect
Creating a query in the database that runs the function and attempting to search its values indirectly causes the same error:
select * from dummy_indirect where Expr1 = 'ABCD1234';
I've attempted to use both ODBC drivers present. ODBCJR32.dll (03/22/2010) and ACEODBC.dll (02/18/2007). To my knowledge these should be current as it was installed with the full Access 2010 and Access 2010 Database Engine.
Any ideas on how to work around this error and achieve the same effect are welcome. Please note, that I cannot alter the database in way, shape, or form. That indirect query was created in another mdb file that has the original tables linked from the original DB.
* Update *
OleDB did not really affect anything.
$dsn= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\dummy.mdb;";
I'm not attempting to use it as a web backend either. I'm not a sadomasochist.
There is a legacy system that I must support that does use Access as a backend. Data gets populated there from other old systems that I must integrate into more modern systems. Hence, the creation of an API with Apache/PHP that is running on the server supporting the legacy system.
I need to be able to search a table that has an alphanumeric case identifier to get a numeric identifier that is unique and tied to a generator (Autonumber in access). Users have been using it a trash box for years (inconsistent data entry with sporadic notations) so the only solution I have is to strip everything except alphanumeric out of both the field value and the search value and attempt to perform a LIKE comparison against it.
If not replace() which is access supported, what ODBC compatible functions exist that I can use do the same kind of comparison?
Just to recap, the Access db engine will not recognize the Replace() function unless your query is run from within an Access application session. Any attempt from outside Access will trigger that "Undefined function" error message. You can't avoid the error by switching from ODBC to OleDb as the connection method. And you also can't trick the engine into using Replace() by hiding it in separate query (in the same or another Access db) and using that query as the data source for your main query.
This behavior is determined by Access' sandbox mode. That linked page includes a list of functions which are available in the default sandbox mode. That page also describes how you can alter the sandbox mode. If you absolutely must have Replace() available for your query, perhaps the lowest setting (0) would allow it. However, I'm not recommending you do that. I've never done it myself, so don't know anything about the consequences.
As for alternatives for Replace(), it would help to know about the variability in the values you're searching. If the space or dash characters appear in only one or a few consistent positions, you could do a pattern match with a Like expression. For example, if the search field values consist of 4 letters, an optional space or dash, followed by 4 digits, a WHERE clause like this should work for the variations of "ABCD1234":
SELECT * FROM dummy
WHERE
data1 = 'ABCD1234'
OR data1 Like 'ABCD[- ]1234';
Another possibility is to compare against a list of values:
SELECT * FROM dummy
WHERE
data1 IN ('ABCD1234','ABCD 1234','ABCD-1234');
However if your search field values can include any number of spaces or dashes at any position within the string, that approach is no good. And I would look real hard for some way to make the query task easier:
You can't clean the stored values because you're prohibited from altering the original Access db in any way. Perhaps you could create a new Access db, import the data, and clean that instead.
Set up the original Access db as a linked server in SQL Server and build your query to take advantage of SQL Server features.
Surrender. :-( Pull in a larger data set to your PHP client code, and evaluate which rows to use vs. which to ignore.
I'm not sure you can do this with ODBC and your constraints. The MS Access driver is limited (by design; MS wants you to use SQL Server for back ends).
Can you use OLEDB? that might be an option.

DEFAULT clause in ALTER TABLE statement resulting in syntax error

I have a customer who would like a customization to an old, Visual Basic 5 application which uses an Access 97 database and Jet 3.5 as the database engine.
The desired customization requires a column to be added to an existing table. The following works fine:
strSQL = "ALTER TABLE Users ADD COLUMN Status BYTE"
pdbDatabase.Execute strSQL
However, I would like to set a default value (i.e. either 0 or 1) for the new column. I have tried the following and a number of variations:
strSQL = "ALTER TABLE Users ADD COLUMN Status BYTE DEFAULT 1"
But they all result in an error stating, "Syntax error in ALTER TABLE statement. (3293)"
In researching this problem, I've seen some information which eludes to the DEFAULT clause not being supported in my antiquated configuration of Access 97 and Jet 3.5.
Can anyone confirm this or point me in the right direction to get this to work?
Thanks for your help.
You could do this by using the DAO object.
Microsoft says this about modifying Access tables:
In addition, certain types of Microsoft Access-specific properties, such as the ValidationRule and DefaultValue properties of fields, can be set only through the Microsoft Access user interface or through DAO in code.
You can read more about it at the link below. There are examples although I didn't see where they specifically show using the DefaultValue property.
http://technet.microsoft.com/en-us/library/cc966376.aspx
Per Access 97/Jet 3.5 SQL documentation no mention of the DEFAULT clause is made when describing the ALTER Table or CREATE Table statements. It is described as a new feature of Jet 4.0 here: http://support.microsoft.com/kb/275561
The only way that I know for sure is to set a default value is to open up the table design in the gui and then under field properties enter a default value. Do you have access to an installation of Access 97?
Though, I'm also guessing that with VB/VBA you can probably access the default value property for the field and set or modify - just not using sql.