Unique Constraint in Visual Studio SQL Designer - sql

I was looking at ways to make a newly added column a Unique but not primary column. I had a look at this W3School link. But Instead of following their approach I simply changed my table in the Visual Studio designer as.
CREATE TABLE [dbo].[Userpro] (
[Id] INT NOT NULL IDENTITY,
[Name] NVARCHAR (50) NULL,
[Postcode] NVARCHAR (4) NULL,
[Gender] INT NULL,
[Blog] NVARCHAR (MAX) NULL,
[FeedBack] NVARCHAR (MAX) NULL,
[Username] NVARCHAR (50) NOT NULL Unique,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Notice that I simply added "Unique" [Username] NVARCHAR (50) NOT NULL Unique. I am unsure if this has the same effect or should I go back and just use the script in the link.

That is perfect.
Adding UNIQUE will have the effect you describe. It is also explained in the link you provide.

Related

Why does my row size exceed the allowed maximum of 8060 bytes

I have the following table in SQL Server 2012, Web Edition:
CREATE TABLE [dbo].[MyTable]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Created] DATETIME DEFAULT (getdate()) NOT NULL,
[RefId] INT NULL,
[Name] NVARCHAR (128) NULL,
[Email] NVARCHAR (128) NULL,
[ImageUrl] NVARCHAR (256) NULL,
[Url] VARCHAR (256) NULL,
[Age] TINYINT NULL,
[Country] VARCHAR (6) NULL,
[Location] NVARCHAR (192) NULL,
[People] INT NULL,
[Categories] NVARCHAR (128) NULL,
[Block] BIT DEFAULT ((0)) NOT NULL,
[GeneratedRevenue] INT NULL,
[IsFemale] BIT DEFAULT ((1)) NULL,
[HasInstalled] BIT NULL,
[Keywords] VARCHAR (128) NULL,
[Brands] NVARCHAR (512) NULL,
[Source] TINYINT NULL,
[Alias] VARCHAR (65) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
As far as I gather, the total size should be 3175 bytes; but I regularly get the following error, when updating the table:
Cannot create a row of size 8068 which is greater than the allowable maximum row size of 8060.
How does the above result in a row size of 8068?
Edit: I should mention that this table has been altered, uses Change Tracking and has four indexes.
Also, if I copy the contents to a new table with the same definition, no errors occur for a while, but do come back.
You say you use Change Tracking. Are you - by any chance - ignoring the versioning part of Change Tracking, and resetting the entries by doing the following?
ALTER TABLE dbo.MyTable disable change_tracking
ALTER TABLE dbo.MyTable enable change_tracking
If so, you may have a suspect. Change Tracking adds an 8 bit column behind the scenes every time you reenable Change Tracking, which is dropped if it already exists. Since dropping a column is just a meta operation, you may have a large number of dropped 8 bit columns lurking behind the scenes, depending on the frequency with which you reenable Change Tracking.
To check this, look at the system_internals_partition_columns view and see if you have a large number of is_dropped colums. There could be more reasons for having many of those, but this way of using Change Tracking is one of them.
I see Remus Rusanu is linking to a good article in a comment (rusanu.com/2011/10/20/sql-server-table-columns-under-the-hoo‌​d): the queries he lists should be what you need to see if the above is the case.
Edit:
In case you need to delete the dropped columns, you can rebuild the clustered index for the table(s) that have many dropped columns. This means that rebuilding the clustered index for MyTable will relieve you of your symptom.

Cannot insert the value NULL into column 'Id' although Id is set

I have a strange problem.
I want to insert an item to a table from database. I use Entity Framework.
Although the Id is set, I keep getting the following error:
Cannot insert the value NULL into column 'Id', table 'project_atp.dbo.ShoppingCarts'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
The table definition:
CREATE TABLE [dbo].[ShoppingCarts] (
[Id] INT NOT NULL,
[Guid] UNIQUEIDENTIFIER NULL,
[Name] NVARCHAR (255) NULL,
[Code] NVARCHAR (255) NULL,
[SupplierNo] NVARCHAR (255) NULL,
[SupplierName] NVARCHAR (255) NULL,
[Price] NVARCHAR (50) NULL,
[Quantity] INT NULL,
CONSTRAINT [PK_ShoppingCarts] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Can you please advise what could be wrong here! Thanks!
By default Entity Framework assumes that an integer primary key is database generated. As the result Entity Framework would not include Primary Key field in the actual INSERT statement.
I would try to either play along and ALTER the table to auto-generate the ID (which judging by your comment you did)
or set StoreGeneratedPattern property of OnlineCarStore.Models.ShoppingCarts Id column to 'None'
or use annotation: [DatabaseGenerated(DatabaseGeneratedOption.None)].

The model already has an element that has the same name - ASP.NET

I'm working with ASP.Net web application and whenever I tried to add a FOREIGN KEY this error appears in the Data tools operations :
SQL71508 :: The model already has an element that has the same name
dbo.FK_Sellers_Users. SQL71508 :: The model already has an element
that has the same name dbo.FK_Sellers_Users.
I don't understand what's the problem with FK! I have 2 tables with this error
table Sellers :
CREATE TABLE [dbo].[Sellers] (
[Seller_ID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[SUsername] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (50) NOT NULL,
[SEmail] NVARCHAR (50) NOT NULL,
[Phone] NVARCHAR (50) NOT NULL,
[City] NVARCHAR (50) NOT NULL,
[LastLoginDate] DATETIME NULL,
[CreatedDate] DATETIME NULL,
PRIMARY KEY CLUSTERED ([Seller_ID] ASC),
CONSTRAINT [FK_Sellers_Users] FOREIGN KEY ([SEmail]) REFERENCES [Users]([Email]),
CONSTRAINT [FK_Sellers_Users] FOREIGN KEY ([SUsername]) REFERENCES [Users]([Username])
);
and table Users :
CREATE TABLE [dbo].[Users] (
[Id] INT NOT NULL IDENTITY,
[Username] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (50) NOT NULL,
[Email] NVARCHAR (50) NOT NULL,
[UserType] INT NULL,
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [AK_Users_Username] UNIQUE ([Username]),
CONSTRAINT [AK_Users_Email] UNIQUE ([Email]),
);
Right there in your CREATE TABLE statement for dbo.Sellers, you have two FK constraints named FK_Sellers_Users.
Make those names unique, perhaps by adding the column name on the end.
You have two foreign keys with the same name FK_Sellers_Users. You should better use FK_Sellers_Users_Email and FK_Sellers_Users_Username.
Actually, this has to do with data that was already entered. Some of the PK and FK data that were entered before might have the same values. You need to delete those first and make the changes you need.
If your project uses SSDT (SQL Server Data Tools), you probably have a foreign key defined in a folder for Keys. Look in "DB Name\Schema Objects\Schemas\dbo\Tables\Keys."
Then Look in the table definition. "DB Name\Schema Objects\Schemas\dbo\Tables". The key could be defined in BOTH places.

an error occured while the batch was being executed

I'm trying to make a simple table in a database.
CREATE TABLE [dbo].[klanten]
(
[Klant_naam] TEXT NOT NULL PRIMARY KEY,
[Klant_adres] TEXT NULL,
[klant_gsm] TEXT NULL,
[klant_gewicht] INT NOT NULL,
[klant_lengte] INT NOT NULL,
[klant_klacht] TEXT NOT NULL
)
When I try to update it, the following error pops-up.
As the documentation warns:
ntext , text, and image data types will be removed in a future version
of Microsoft SQL Server. Avoid using these data types in new
development work, and plan to modify applications that currently use
them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
So, try this instead:
CREATE TABLE [dbo].[klanten] (
[Klant_naam] varchar(max) NOT NULL PRIMARY KEY,
[Klant_adres] varchar(max) NULL,
[klant_gsm] varchar(max) NULL,
[klant_gewicht] INT NOT NULL,
[klant_lengte] INT NOT NULL,
[klant_klacht] varchar(max) NOT NULL
)
Well, this doesn't quite work either, because there is a limit of 900 bytes for index keys. How about using a surrogate key and reasonable column lengths?
CREATE TABLE [dbo].[klanten] (
Klant_Id int not null identity(1, 1) primary key,
[Klant_naam] varchar(255) NOT NULL unique,
[Klant_adres] varchar(max) NULL,
[klant_gsm] varchar(max) NULL,
[klant_gewicht] INT NOT NULL,
[klant_lengte] INT NOT NULL,
[klant_klacht] varchar(max) NOT NULL
);
Try to change "TEXT" data type to "NCHAR()" or any other similar to this.
This error usually occured when you try to update database, but some fields can't be updated. For example, I have 5 fields in a table:
[Id] INT IDENTITY (1, 1) NOT NULL,
[Path] NVARCHAR (MAX) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Url] NVARCHAR (MAX) NULL,
[SecureUrl] NVARCHAR (MAX) NULL
I've worked for some time with it, and make some records. And some of them have value NULL at [Url]. Suddenly I decide to change table:
[Id] INT IDENTITY (1, 1) NOT NULL,
[Path] NVARCHAR (MAX) NOT NULL,
[Name] NVARCHAR (50) NULL,
[Url] NVARCHAR (MAX) NOT NULL, //!!! HERE A PROBLEM, I ALREADY HAVE NULL RECORDS IN DATA
[SecureUrl] NVARCHAR (MAX) NULL
Problem is that my data has been made with the old model and it has records with the NULL at [Url], but in new model NULL value can't be at [Url]. So as with new model, old data can't be correct. Thus we have the error when update.

How to reference two tables in Visual Studio 2012 by adding foreign key?

I have a problem adding a foreign key to a table column.
My tables look this way. I need to reference ContactOwnerId from Contact table to UserId in UserProfile table
CREATE TABLE [dbo].[Contacts] (
[ContactId] INT IDENTITY (1, 1) NOT NULL,
[ContactOwnerId] INT NOT NULL,
[FirstName] NVARCHAR (MAX) NOT NULL,
[LastName] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
[City] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([UserId]) REFERENCES [Contacts]([ContactOwnerId])
);
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (56) NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC),
UNIQUE NONCLUSTERED ([UserName] ASC)
);
I added a foreign key, but it seems, not right, because UserId is highlighted, giving error:
SQL71501 :: Foreign Key: [dbo].[FK_Contacts_UserProfile] has an unresolved reference to Column [dbo].[Contacts].[UserId].
SQL71516 :: The referenced table '[dbo].[Contacts]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
How do I correctly reference these two tables? Thanks in advance.
EDIT
I did like sgeddes said. But I get an error, when I try to create a contact.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contacts_UserProfile". The conflict occurred in database "ContactAppContext", table "dbo.UserProfile", column 'UserId'.
The statement has been terminated.
If I remove a foreign key I get no error.
What I want to achieve is, when a user creates contacts, his Id(UserId) could associate with ContactOwnerId, so that contacts could relate to one specific user.
Since ContactOwnerId in the Contact table should be the FOREIGN KEY, you need to specify that in your CONSTRAINT instead of UserId.
I think this is what you're trying to do:
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (56) NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC),
UNIQUE NONCLUSTERED ([UserName] ASC)
);
CREATE TABLE [dbo].[Contacts] (
[ContactId] INT IDENTITY (1, 1) NOT NULL,
[ContactOwnerId] INT NOT NULL,
[FirstName] NVARCHAR (MAX) NOT NULL,
[LastName] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
[City] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Contacts] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_Contacts_UserProfile] FOREIGN KEY ([ContactOwnerId]) REFERENCES [UserProfile]([UserId])
);
The problem was with the last line. You need to reference the column from the Contacts table first, and then point to your UserProfile table. You had that backwards.
Here's a SQL Fiddle
Here's some documentation/examples for creating FOREIGN KEY CONSTRAINTS:
http://msdn.microsoft.com/en-us/library/aa258255(v=sql.80).aspx