I have made multiple attempts at creating a SQL Server table to link to an Access front-end with 'disallow zero length value' constraints on the table but when I link the table up to my front-end the design of the table shows Allow Zero Length = Yes
Now I have tried various methods of trying to change this to No (I need it to be No for a migration project I am working on). I am not sure what needs to be done on the SQL Server to ensure that upon linking this table to my access front-end, this constraint is a No.
This is the Create script for my table:
Create Table Riku(
ID int NOT NULL PRIMARY KEY,
testtext varchar(255),
CONSTRAINT DissalowNulls
CHECK (testtext <> ''),
CONSTRAINT DissalowNull2
CHECK (LEN(testtext) = 0)
);
Neither of these two constraints work. I have tried using Nvarchar, Varchar, and Text as SQL Data Type all of which yielded this same result (Yes).
Any ideas?
You must indicate to the column that does not allow null
Create Table Riku(
ID int NOT NULL PRIMARY KEY,
testtext varchar(255) NOT NULL,
CONSTRAINT DissalowNulls
CHECK (testtext <> '')
);
I am interpreting your question as:
"Why is it when I create a constraint in SQL Server to 'DisalowNulls'
does it not appear that way when viewing the table properties in
Access?"
My answer to that questions is, "they are not syntax equivalent features". When Access interprets the design of the linked table it is not perceiving these as the same property. The constraint you created in SQL Server is more equivalent to an Access Validation Rule although that will also not appear in the Access table designer.
It would be nice if Access would disable properties that aren't relevant to the database type of the linked table. Other properties like Format, Input Mask, and Caption could also be in that category.
Related
The query to create the table with its respective field set as IDENTITY is the following:
CREATE TABLE user (
email varchar(100) primary key
name varchar(30),
pwd varchar(10)
)
Alter table to add IDENTITY field:
ALTER TABLE user ADD id int /*NOT NULL*/ IDENTITY;
The email field to be PRIMARY KEY INDEX will fail if a NULL or DUPLICATED value was set, for example supposed that myemail#domain.com already exists, OK the query fails, but I change the email to anotheremail#domain.com SQL Server generate a new one value for the IDENTITY field based on the query(s) that failed before. My question is why does this happen? (Is this ONLY on SQL Server or other database providers also)
Well, this is clearly documented in "CREATE TABLE (Transact-SQL) IDENTITY (Property)":
Reuse of values - For a given identity property with specific seed/increment, the identity values are not reused by the engine. If a particular insert statement fails or if the insert statement is rolled back then the consumed identity values are lost and will not be generated again. This can result in gaps when the subsequent identity values are generated.
Further along the documentation also answers why and suggests what to do if this is not acceptable:
These restrictions are part of the design in order to improve performance, and because they are acceptable in many common situations. If you cannot use identity values because of these restrictions, create a separate table holding a current value and manage access to the table and number assignment with your application.
I have a table named myTable on SQL Server 2008 R2 Express.
I would like to have a (marital) Status column with the only explicit values: 'Single', 'Married', 'Divorced', 'Widower'.
The default should be 'Married'.
Is there a way to limit the field to the above values ON THE SQL Server without additional tables?
You can do that with a CHECK() constraint.
create table whatever (
...
Status varchar(12) not null default 'Married'
check (Status in ('Single', 'Married', 'Divorced', 'Widower')),
...
);
The problem with using a CHECK constraint like this is that it's harder for the user interface to present a list of valid choices to the user for selection. If these four were stored in a table of marital statuses, you could just select status from marital_statuses order by status;. If they were stored in a table, you could still use 'Married' as the default.
If I were going to store these in a table, it might look like this.
create table marital_statuses (
status_code char(1) primary key,
status_text varchar(12) not null unique
);
insert into marital_statuses values
('s', 'Single'),
('m', 'Married'),
('d', 'Divorced'),
('w', 'Widower');
Using human-readable codes means you usually won't need an additional join. (If you use ID numbers, you always need an additional join.) If I did that, I'd use a foreign key in the "whatever" table, and change the default to 'm'.
CHECK column constraints might fit your requirements - I don't know how well they work with character strings. See MSDN reference
I have a number of tables I need to convert from mySQL to SQL Server.
An Example of a mySQL Table is
CREATE TABLE `required_items` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique Barcode ID',
`fk_load_id` INT( 11 ) NOT NULL COMMENT 'Load ID',
`barcode` VARCHAR( 255 ) NOT NULL COMMENT 'Barcode Value',
`description` VARCHAR( 255 ) NULL DEFAULT NULL COMMENT 'Barcode Description',
`created` TIMESTAMP NULL DEFAULT NULL COMMENT 'Creation Timestamp',
`modified` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Modified Timestamp',
FOREIGN KEY (`fk_load_id`) REFERENCES `loads`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET ascii COLLATE ascii_general_ci COMMENT = 'Contains Required Items for the Load';
And a trigger to update the created date
CREATE TRIGGER required_items_before_insert_created_date BEFORE INSERT ON `required_items`
FOR EACH ROW
BEGIN
SET NEW.created = CURRENT_TIMESTAMP;
END
Now I need to create tables similar to this in SQL Server. There seems to be a lot of different data types available so I am unsure which to use.
What data type should I use to the primary key column
(uniqueidentifier, bigint, int)?
What should I use for the timestamps
(timestamp, datatime, datetime2(7))?
How should I enforce the created
and modified timestamps (currently I am using triggers)?
How can I enforce foreign key constraints.
Should I be using Varchar(255) in SQL Server? (Maybe Text, Varchar(MAX) is better)
I am using Visual Studio 2010 to create the tables.
First of all, you can probably use PHPMyAdmin (or something similar) to script out the table creation process to SQL Server. You can take a look at what is automatically created for you to get an idea of what you should be using. After that, you should take a look at SSMS (SQL Server Management Studio) over Visual Studio 2010. Tweaking the tables that your script will create will be easier in SSMS - in fact, most database development tasks will be easier in SSMS.
What data type should I use to the primary key column (uniqueidentifier, bigint, int)?
Depending on how many records you plan to have in your table, use int, or bigint. There are problems with uniqueidentfiers that you will probably want to avoid. INT vs Unique-Identifier for ID field in database
What should I use for the timestamps (timestamp, datatime, datetime2(7))?
timestamps are different in SQL Server than in MySQL. Despite the name, a timestamp is an incrementing number that is used as a mechanism to version rows. http://msdn.microsoft.com/en-us/library/ms182776%28v=sql.90%29.aspx . In short though, datetime is probably your best bet for compatibility purposes.
How should I enforce the created and modified timestamps (currently I am using triggers)?
See above. Also, the SQL Server version of a "Timestamp" is automatically updated by the DBMS. If you need a timestamp similar to your MySQL version, you can use a trigger to do that (but that is generally frowned upon...kind of dogmatic really).
How can I enforce foreign key constraints.
You should treat them as you would using innoDB. See this article for examples of creating foreign key constraints http://blog.sqlauthority.com/2008/09/08/sql-server-%E2%80%93-2008-creating-primary-key-foreign-key-and-default-constraint/
Should I be using Varchar(255) in SQL Server? (Maybe Text, Varchar(MAX) is better)
That depends on the data you plan to store in the field. Varchar max is equivalent to varchar(8000) and if you don't need varchar(255), you can always set it to a lower value like varchar(50). Using a field size that is too large has performance implications. One thing to note is that if you plan to support unicode (multilingual) data in your field, use nvarchar or nchar.
I am mass updating a SQL Server database. I am changing all our numeric(38,0) columns to int (yes, SQL Server scripts were created from Oracle scripts).
Using SMO and C# (I am a sw engineer), I managed to generate really nice scripts like SQL Server Management Studio would.
It all works very nicely except for one particular issue:
For a handful of tables, when I call
ALTER TABLE [myTable] ALTER COLUMN [columnA] INT
it decides to also change the column from NOT NULL to NULL. That, of course is a huge issue since I need to regenerate primary keys for most of those tables on those particular columns.
Obviously, I have plenty of options using SMO to find out which columns are primary keys and force them to be NOT NULL after or while I am updating the data type, but I am really curious as to what can be causing this.
Regards,
Eric.
Because in the absense of NOT NULL, the default is NULL.
ALTER TABLE [myTable]
ALTER COLUMN [columnA] INT NOT NULL
from ALTER TABLE (Transact-SQL)
When you create or alter a table with
the CREATE TABLE or ALTER TABLE
statements, the database and session
settings influence and possibly
override the nullability of the data
type that is used in a column
definition. We recommend that you
always explicitly define a column as
NULL or NOT NULL for noncomputed
columns.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I create unique constraint that also allows nulls in sql server
I have a table where I need to force a column to have unique values.
This column must be nullable and by business logic multiple NULL values should be permitted, whereas other duplicate values are not.
SQL Server UNIQUE constraint is no good in this situation because it considers NULL as regular values, so it will reject duplicate NULLs.
Currently, value uniqueness is granted by the BLL so I'm not looking for a dirty hack to make it work.
I just would like to know if there is a clean solution to enforce this constraint in the DB.
And yeah, I know I can write a trigger to do that: is a trigger the only solution? (or the best solution anyway?)
If you're using SQL Server 2008 (won't work for earlier version) there is the concept of a filtered index. You can create the index on a filtered subset of the table.
CREATE UNIQUE INDEX indexName ON tableName(columns) INCLUDE includeColumns
WHERE columnName IS NOT NULL
Duplicate of this question?
The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:
CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)
Works on SQL Server 2000. You may need ARITHABORT on e.g.
ALTER DATABASE MyDatabase SET ARITHABORT ON
If you're using SQL Server 2008, have a look into Filtered Indexes to achieve what you want.
For older version of SQL Server, a possible alternative to a trigger involves a computed column:
Create a computed column which uses the value of your "unique" column if it's not NULL, otherwise it uses the value of the row's Primary Key column (or any column which will be unique).
Apply a UNIQUE constraint to the computed column.
http://www.sqlmag.com/article/articleid/98678/sql_server_blog_98678.html
will work only in Microsoft SQL Server 2008
You can create a view in which you select only not null values and create an index on it.
Here is the source - Creating Indexed Views
You should use UNIQUEIDENTIFIER in that column, can be NULL and also is unique by definition.
Hope that helps.