Unique constraint on another column if not null - sql

I want to create this table with the following constrains, is it possible to do with SQL Server Management Studio?
Id
ProductId [Nullable column]
CompanyId [Nullable column]
Username [unique for every productId - IF DeletedAt is not NULL]
Identifier [Nullable column] [unique for every companyId - IF DeletedAt is not NULL]
DeletedAt [Nullable column]
Update:
My table create query is the following:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProductId] [int] NULL,
[CompanyId] [int] NULL,
[Username] [nvarchar](max) NOT NULL,
[Identifier] [nvarchar](max) NULL,
[DeletedAt] [datetime2](7) NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

You'll want to use a unique filtered index. Here you go for the table:
/****** Object: Table [dbo].[the_table] Script Date: 7/26/2018 4:04:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[the_table](
[id] [int] NOT NULL,
[productid] [varchar](50) NULL,
[companyid] [varchar](50) NULL,
[username] [varchar](50) NULL,
[identifier] [varchar](50) NULL,
[deleteat] [varchar](50) NULL,
CONSTRAINT [PK_the_table] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
And the index for username:
SET ANSI_PADDING ON
GO
/****** Object: Index [UIDX_USERNAME] Script Date: 7/26/2018 4:03:31 PM ******/
CREATE NONCLUSTERED INDEX [UIDX_USERNAME] ON [dbo].[the_table]
(
[username] ASC
)
WHERE ([DELETEAT] IS NOT NULL)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
It would be the same index logic for the other column, but I don't want to clutter this answer by posting more! I would not mess around with putting the logic in triggers or stored proc's, bad data could still sneak in. If you keep nice constraints, nobody can clutter your data up :)

You can use filtered indexes. The syntax looks like this:
create unique index unq_thetable_username on the_table(username)
where deleteAt is not null;
I don't know if you can point-and-click your way to this solution. I would just write the logic as above.

Create a unique index on ProductId and Username, and use a where clause to restrict that index to WHERE DeletedAt IS NOT NULL. Answer showing an example of a unique filtered index.
You may also need the clause AND ProductId IS NOT NULL, although that wasn't stated as a requirement, but since that column is nullable you ought to think about this.
Similar for Identifier.
You might also want to think about the value of a table where it is valid to have a row where all the columns except Id are null...

Related

Problem with accents in portuguese on varchar column

I have a table with 2 varchar columns. One of this columns has to store the name of an item in portuguese. The problem is when i make an insert, appears some strange letters. Even if i make an update, they still appear.
This is my table definition:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Items](
[idItem] [int] IDENTITY(1,1) NOT NULL,
[name_es] [varchar](100) NULL,
[name_pt] [varchar](100) NULL,
CONSTRAINT [Items] PRIMARY KEY CLUSTERED
(
[idItem] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
And this is what happens
Any idea?
You’re using VARCHAR which doesn’t like non-English characters so try and use the data type NVARCHAR instead

SQL one to many relation table design, the right way

Plot: I need to book an Order which relies on 3 different type of Factory.
I have individual tables for both order and Factory. Now I need to make a one to many relations between Order and Booking Factory.
Order Table:
CREATE TABLE [dbo].[tbl_OrderInformation](
[OrderInformationId] [int] IDENTITY(1,1) NOT NULL,
[OrderId] [int] NOT NULL,
[OrderNo] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_tbl_OrderInformation] PRIMARY KEY CLUSTERED
( [OrderInformationId] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE =
OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Factory Table:
CREATE TABLE [dbo].[tbl_Factory](
[FactoryId] [int] IDENTITY(1,1) NOT NULL,
[FactoryName] [nvarchar](50) NOT NULL,
[FactoryType] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_tbl_Factory] PRIMARY KEY CLUSTERED
( [FactoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Sample Order Data
Sample Factory Data
Now, an Order relies on multiple garments, dyeing, and printing Factory.
Suppose, Order C101 relies on Garments-A, Dyeing-A, Printing-A, Printing-B, Printing-C.
Now, I can design OrderBooking table in 2 ways.
CREATE TABLE [dbo].[tbl_OrderBooking_1](
[OrderBookingId] [INT] IDENTITY(1,1) NOT NULL,
[OrderId] [INT] NOT NULL,
[FactoryId] [INT] NULL,
[FactoryType] [NVARCHAR](50) NULL,
CONSTRAINT [PK_tbl_OrderBooking_1] PRIMARY KEY CLUSTERED
(
[OrderBookingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
This the data will look like below:
And The second way,
CREATE TABLE [dbo].[tbl_OrderBooking_2](
[OrderBookingId] [INT] IDENTITY(1,1) NOT NULL,
[OrderId] [INT] NULL,
[garmentsFactoryId] [INT] NULL,
[dyeingFactoryId] [INT] NULL,
[printingFactoryId] [INT] NULL,
CONSTRAINT [PK_tbl_OrderBooking_2] PRIMARY KEY CLUSTERED
(
[OrderBookingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Here the data will look like,
Now, which approach of designing the OrderBooking table is more accurate and why ?
Please keep in mind that the type of factory is fixed to 3, and OrderBooking table will grow quite large over time thus tend to have heavy read and write operations.
The link table between Order & factory would be the best approach.
You will get better performance and you can create indexes on the numeric columns.
Going forward if you have any new factory then it is also each to insert without any issue.
The link table will help you to align with the Normalization rule as well. so my suggestion is go with that.

The specified schema name either does not exist or you do not have permission to use it

I am trying to create replica of my database from SQL server to another.
For that I am generating script from original server and trying to run in another server. I've created database manually with the same name.
Here is the screenshot of original database
When I generate script, following script is created which I am trying in another server
USE [ContactsApp]
GO
/****** Object: Table [common].[BU] Script Date: 2/12/2016 3:02:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [common].[BU](
[ID] [int] IDENTITY(1,1) NOT NULL,
[IndustryID] [int] NOT NULL,
[BU] [varchar](50) NOT NULL,
[Code] [varchar](2) NOT NULL,
[Active] [bit] NOT NULL,
[CreatedBy] [uniqueidentifier] NOT NULL,
[CreateDate] [date] NOT NULL,
[CreateTime] [time](3) NOT NULL,
[ModifiedBy] [uniqueidentifier] NULL,
[ModifyDate] [date] NULL,
[ModifyTime] [time](3) NULL,
CONSTRAINT [PK_BU] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UK_BU_Code] UNIQUE NONCLUSTERED
(
[Code] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UK_BU_Name] UNIQUE NONCLUSTERED
(
[BU] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [common].[BU] ADD CONSTRAINT [DF_BU_CreateDate] DEFAULT (CONVERT([date],getdate())) FOR [CreateDate]
GO
ALTER TABLE [common].[BU] ADD CONSTRAINT [DF_BU_CreateTime] DEFAULT (CONVERT([time],getdate())) FOR [CreateTime]
GO
ALTER TABLE [common].[BU] WITH CHECK ADD CONSTRAINT [FK_BU_Industry] FOREIGN KEY([IndustryID])
REFERENCES [common].[Industry] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [common].[BU] CHECK CONSTRAINT [FK_BU_Industry]
GO
When I try to run this script, I get following error
The specified schema name "common" either does not exist or you do
not have permission to use it.
I don't know what is the meaning of common here.Thanks
Your tables are 'grouped' (for want of better word) in schemas (google for it). You should run
CREATE SCHEMA common
And likewise for all other schemas.

use two primary keys attribute from a table with different title

I got table "Functions" with Function_ID {PK} and I want another table "Hierarchy" with Hierarchy_ID {PK} which defines tree structure of functions so i need one Function_ID from Function table AS Parent_ID and one Function_ID AS Child. my question is how i can use two primary keys from another table to make it together as Foreign key
I am using SQL Server 2012 and the Management Studio
Many Thanks
Actually you just need to add a ParentFunction_ID column in the Functions table.
You don't need another table if your structure is indeed a tree.
Then make the ParentFunction_ID to be a FK to the same table Functions.
So ParentFunction_ID (FK) would be pointing to Function_ID (PK).
The only record which has ParentFunction_ID NULL would be the root of your tree.
Here is some sample code:
USE [test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Functions](
[Function_ID] [int] IDENTITY(1,1) NOT NULL,
[FunctionCode] [varchar](max) NULL,
[ParentFunction_ID] [int] NULL,
CONSTRAINT [PK_Functions] PRIMARY KEY CLUSTERED
(
[Function_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Functions] WITH CHECK ADD CONSTRAINT [FK_Functions_Functions] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Functions] ([Function_ID])
GO
ALTER TABLE [dbo].[Functions] CHECK CONSTRAINT [FK_Functions_Functions]
GO
Name your Functions table a Function table. AFAIK using
plurals for table names is not really a good practice.
So you can do this.
--- 1 ---
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Function](
[Function_ID] [int] IDENTITY(1,1) NOT NULL,
[FunctionCode] [varchar](max) NULL,
CONSTRAINT [PK_Function] PRIMARY KEY CLUSTERED
(
[Function_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
--- 2 ---
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Hierarchy](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentFunction_ID] [int] NULL,
[ChildFunction_ID] [int] NULL,
CONSTRAINT [PK_Hierarchy] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Hierarchy] WITH CHECK ADD CONSTRAINT [FK_Hierarchy_Function] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO
ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function]
GO
ALTER TABLE [dbo].[Hierarchy] WITH CHECK ADD CONSTRAINT [FK_Hierarchy_Function1] FOREIGN KEY([ChildFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO
ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function1]
GO

SQL Data entities Entity Association

I have about 8 entities that all have a one to one relationship with a common entity.
The client is not choosing from pre-defined data so it is not necessary to apply a FK to be used as a constraint.
The main table in question is call a finish table and it contains four unknown hex colors that are sent from the client to the server.
For example, when a door is built the colors for the different parts of the door and it's outer parts can all have different colors. So, all of these tables in question, their data is always fresh from the client and not chosen from a drop down, or from some other pre-defined data that I am given to the client to choose from.
My question is, what would be the best way to association this finish entity with the other entities that need a way to express their finish?
I am adding a screen shot of a diagram that I am working on, these are not all the entities and are just the ones in question right now and ones that will help articulate to others what I am needing a solution for.
I have also included some script as well.
/****** Object: Table [dbo].[Finish] Script Date: 06/22/2012 15:08:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Finish](
[ID] [int] NOT NULL,
[Left] [varchar](30) NULL,
[Right] [varchar](30) NULL,
[Top] [varchar](30) NULL,
[Bottom] [varchar](30) NULL,
[Note] [varchar](150) NULL,
CONSTRAINT [PK_Finish] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Horizontal] Script Date: 06/22/2012 15:08:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Horizontal](
[ID] [int] IDENTITY(11,1) NOT NULL,
[Name] [varchar](15) NOT NULL,
[Floor] [smallint] NOT NULL,
[SizeID] [int] NOT NULL,
[GlassPocket] [decimal](5, 3) NULL,
[IsFiller] [bit] NOT NULL,
[Note] [varchar](150) NULL,
CONSTRAINT [PK_Horizontal] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Door] Script Date: 06/22/2012 15:08:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Door](
[ID] [int] IDENTITY(421,1) NOT NULL,
[BayID] [int] NOT NULL,
[Position] [tinyint] NOT NULL,
[HasJamb] [bit] NOT NULL,
[HasThreshold] [bit] NOT NULL,
[IsAutoShowroom] [bit] NOT NULL,
[IsSingle] [bit] NOT NULL,
[Type] [varchar](10) NOT NULL,
[SizeID] [int] NOT NULL,
[Note] [varchar](150) NULL,
CONSTRAINT [PK_Door] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Leaf] Script Date: 06/22/2012 15:08:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Leaf](
[ID] [int] IDENTITY(21,1) NOT NULL,
[DoorID] [int] NOT NULL,
[Position] [tinyint] NOT NULL,
[Stile] [varchar](10) NOT NULL,
[Bottomrail] [decimal](5, 3) NOT NULL,
[Hand] [varchar](5) NOT NULL,
[IsActive] [bit] NOT NULL,
[Swing] [varchar](5) NOT NULL,
[SizeID] [int] NOT NULL,
[Note] [varchar](150) NULL,
CONSTRAINT [PK_Leaf] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Bay] Script Date: 06/22/2012 15:08:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Bay](
[ID] [int] IDENTITY(1213,1) NOT NULL,
[ElevationID] [int] NOT NULL,
[Position] [tinyint] NOT NULL,
[SizeID] [int] NOT NULL,
[Note] [varchar](150) NULL,
CONSTRAINT [PK_Bay] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Each one of the entities below need to be associated with the finish table. Each entity new record has exactly one finish relationship.
Is it possible to associate these and still be able to do a Cascade On DELETE, with-out having a circular reference issues?
Yes, it's possible.
You would add a reference to Finish entity in each of the tables that has a relationship to it.
You would define the column with the same datatype, (and normally) as the referenced_table_name and id. In our shop, the column_name would be [finish_id]. (I see here that you are using a CamelCase style.)
At any rate, I would recommend you define this as a foreign key.
You say there is no need to, but from what you describe, this is exactly the kind of situation that calls for a foreign key constraint.
You need to decide on the action when the id in the finish table is updated or deleted. (Do you want to disallow the update or delete? Do you want to preserve existing relationship?) I expect you would want the default ON DELETE RESTRICT. You could allow for updates, and preserve the relationships, with ON UPDATE CASCADE.)
I don't see any potential problem with circular references, as long as the finish table will be the parent (all the other tables reference it, and the finish table doesn't have any references to the other tables.)