Related
I have the below table definition and I want to add system versioning to it but I can't seem to get it into the WITH clause without SQL Server complaining.
CREATE TABLE [dbo].[Employee](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[SysStartTime] [datetime2](7) NOT NULL,
[SysEndTime] [datetime2](7) NOT NULL,
CONSTRAINT [PK_Employee_1] PRIMARY KEY CLUSTERED
(
[EmployeeId] 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's the system versioning WITH clause.
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[EmployeeHistory], DATA_CONSISTENCY_CHECK=ON));
It's probably easiest and most succinct to create your table and then add the required system versioning elements:
create table [dbo].[Employee](
[EmployeeId] [int] identity(1,1) not null,
[FirstName] [varchar](50) null,
[LastName] [varchar](50) null
constraint [PK_Employee_1] primary key clustered
(
[EmployeeId] asc
)with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [PRIMARY]
) on [PRIMARY]
alter table dbo.Employee add
SysStartTime datetime2 generated always as row start constraint DF_EmployeeSysStart default SysUtcDateTime(),
SysEndTime datetime2 generated always as row end constraint DF_EmployeeSysEnd default Convert(datetime2, '9999-12-31 23:59:59.9999999'),
period for system_time (SysStartTime,SysEndTime);
alter table Employee set (system_versioning = on (history_table = dbo.EmployeeHistory, data_consistency_check=on));
Edit
To combine in a single create table
create table [dbo].[Employee](
[EmployeeId] [int] identity(1,1) not null,
[FirstName] [varchar](50) null,
[LastName] [varchar](50) null,
[SysStartTime] datetime2 generated always as row start constraint DF_EmployeeSysStart default SysUtcDateTime(),
[SysEndTime] datetime2 generated always as row end hidden constraint DF_EmployeeSysEnd default Convert(datetime2, '9999-12-31 23:59:59.9999999'),
period for system_time (SysStartTime,SysEndTime),
constraint [PK_Employee_1] primary key clustered ( [EmployeeId] asc) with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on)
) with ( system_versioning = on (history_table = dbo.EmployeeHistory, data_consistency_check=on))
I am creating the following table:
CREATE TABLE [dbo].[AD_Group_Members]
(
[AD_GROUP] [varchar](100) NOT NULL,
[MEMBER_ID] [varchar](100) NOT NULL,
[MEMBER_NAME] [varchar](100) NULL,
[ADDED] [datetime] NULL,
[REMOVED] [datetime] NULL,
[CHECKED] DATETIME NOT NULL DEFAULT(GETDATE()), --Checking to see if Removed is NULL, then it is a valid record.
CONSTRAINT [PK_AD_Group_Members]
PRIMARY KEY CLUSTERED ([MEMBER_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]
Per the comment, is it possible to make the CHECKED column timestamp so long REMOVED column is NULL?
I know this kind of problem can happen but I have no idea on figuring it out (also, it is in Portuguese, so I will try my best to illustrate my question in English, translating the database structure, fields, etc).
These are the 4 tables that I need for this query:
- Agenda_Cliente (this is the Client table);
- Agenda_Imposto (this is the Taxes table - description for each tax ID);
- Agenda_ClienteImposto (NxN table - relates each Client to the taxes he or she pays);
- Agenda_LogAgenda (that's the core of the query: it contains which tax (by ID: CodigoImposto) was sent to a specific client (by ID as well: CodigoCliente), when the tax was sent (DataHoraEnvio) and when it was accessed (DataHoraAcesso).
The strctures are the following:
CREATE TABLE [dbo].[Agenda_Cliente](
[CodigoCliente] [bigint] IDENTITY(1,1) NOT NULL,
[CodigoEscritorio] [int] NOT NULL,
[RazaoSocial] [varchar](60) NOT NULL,
[NomeFantasia] [varchar](60) NOT NULL,
[Email] [varchar](60) NOT NULL,
[TelefoneComercial] [bigint] NOT NULL,
[TelefoneCelular1] [bigint] NOT NULL,
[TelefoneCelular2] [bigint] NOT NULL,
[CnpjCpf] [bigint] NOT NULL,
[Cep] [int] NOT NULL,
[Endereco] [varchar](80) NOT NULL,
[Bairro] [varchar](60) NOT NULL,
[Municipio] [varchar](60) NOT NULL,
[Estado] [char](2) NOT NULL,
[RegimeTributacao] [int] NOT NULL,
[FlagAtivo] [bit] NOT NULL,
PRIMARY KEY CLUSTERED
(
[CodigoCliente] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Agenda_Imposto](
[CodigoImposto] [int] IDENTITY(1,1) NOT NULL,
[DescricaoImposto] [varchar](30) NOT NULL,
[TipoImposto] [int] NOT NULL,
[DeptoResponsavel] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[CodigoImposto] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Agenda_ClienteImposto](
[CodigoClienteImposto] [bigint] IDENTITY(1,1) NOT NULL,
[CodigoCliente] [bigint] NOT NULL,
[CodigoImposto] [int] NOT NULL,
[DataLimite] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[CodigoClienteImposto] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Also, the FOREIGN KEYS are all OK and working.
So, the problem is: I have the following SQL SELECT query:
SELECT c.CnpjCpf, c.NomeFantasia, i.DescricaoImposto, ci.DataLimite, la.DataHoraEnvio, la.DataHoraAcesso
FROM Agenda_Cliente c
JOIN Agenda_ClienteImposto ci ON ci.CodigoCliente = c.CodigoCliente
JOIN Agenda_Imposto i ON i.CodigoImposto = ci.CodigoImposto
LEFT JOIN Agenda_LogAgenda la ON la.CodigoImposto = i.CodigoImposto
WHERE c.CodigoEscritorio = 1
ORDER BY c.NomeFantasia ASC, ci.DataLimite ASC
It's bringing me this:
But I need it to bring me this:
And if I SELECT * at the Calendar log (Agenda_LogAgenda), there's only one record.
It seems to me that it's something to do with Agenda_ClienteImposto, as far as I tried here, but it may be something about the JOIN clause that I'm not getting, because it's applying the result for "Empresa 1" in "Empresa 3", but "Empresa 3" does not exist in Agenda_LogAgenda.
Any help is appreciated.
Thanks!
The left join to Agenda_LogAgenda is only on CodingoImposto. From the values in the query, 'CRF' probably does exist. Add NomFantasia to the ON clause of the left join.
I have 2 tables. Problem is I always get multiple records no matter what I do.
Pages
SubMenus
Relation is 1 to 1 (each submenu has a page)
SubMenus sample data:
submenu_id parentmenu_id display_name url_name
----------------------------------------------------
1 1 Home home
2 1 Contact contact
Pages table data:
page_id submenu_id page_title url_name
---------------------------------------------------------
1 1 Home Page home
2 1 Contact Page null
I want to retrieve single value from there JOIN where SubMenu.UrlName == Home
(from s in SubMenus
join p in Pages on s.Id equals p.SubMenuId
where s.UrlName == "home"
select new
{
s.Id, s.UrlName,
PageId = p.Id, p.Title, p.Html,
p.MetaAuthor, p.MetaKeywords, p.MetaDescription
}).FirstOrDefault();
But if I check the SQL and run it. I get single record without any problem. Below is what SQL generated
SELECT TOP (1)
[Extent1].[submenu_id] AS [submenu_id],
[Extent1].[url_name] AS [url_name],
[Extent2].[page_id] AS [page_id],
[Extent2].[page_title] AS [page_title],
[Extent2].[page_html] AS [page_html],
[Extent2].[meta_author] AS [meta_author],
[Extent2].[meta_keywords] AS [meta_keywords],
[Extent2].[meta_description] AS [meta_description]
FROM
[dbo].[SubMenu] AS [Extent1]
INNER JOIN
[dbo].[Pages] AS [Extent2] ON [Extent1].[submenu_id] = [Extent2].[submenu_id]
WHERE
N'home' = [Extent1].[url_name]
Table structure:
CREATE TABLE [dbo].[ParentMenu]
(
[parentmenu_id] [int] IDENTITY(1,1) NOT NULL,
[group_name] [nvarchar](50) NULL,
[title] [nvarchar](100) NULL,
[active] [bit] NOT NULL,
[index_order] [int] NULL,
CONSTRAINT [PK_ParentMenu]
PRIMARY KEY CLUSTERED ([parentmenu_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].[ParentMenu]
ADD CONSTRAINT [DF_ParentMenu_active] DEFAULT ((1)) FOR [active]
GO
ALTER TABLE [dbo].[ParentMenu]
ADD CONSTRAINT [DF_ParentMenu_index_order] DEFAULT ((0)) FOR [index_order]
GO
CREATE TABLE [dbo].[SubMenu]
(
[submenu_id] [int] IDENTITY(1,1) NOT NULL,
[parentmenu_id] [int] NOT NULL,
[display_name] [nvarchar](100) NULL,
[url_name] [nvarchar](100) NULL,
[index_order] [int] NULL,
[active] [bit] NOT NULL,
CONSTRAINT [PK_SubMenu]
PRIMARY KEY CLUSTERED ([submenu_id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_SubMenu_1]
UNIQUE NONCLUSTERED ([url_name] 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].[SubMenu] WITH CHECK
ADD CONSTRAINT [FK_SubMenu_ParentMenu]
FOREIGN KEY([parentmenu_id]) REFERENCES [dbo].[ParentMenu] ([parentmenu_id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SubMenu] CHECK CONSTRAINT [FK_SubMenu_ParentMenu]
GO
ALTER TABLE [dbo].[SubMenu]
ADD CONSTRAINT [DF_SubMenu_index_order] DEFAULT ((0)) FOR [index_order]
GO
ALTER TABLE [dbo].[SubMenu]
ADD CONSTRAINT [DF_SubMenu_active] DEFAULT ((1)) FOR [active]
GO
CREATE TABLE [dbo].[Pages]
(
[page_id] [int] IDENTITY(1,1) NOT NULL,
[submenu_id] [int] NOT NULL,
[page_title] [nvarchar](200) NULL,
[url_name] [nvarchar](100) NULL,
[page_html] [nvarchar](max) NULL,
[meta_author] [nvarchar](300) NULL,
[meta_keywords] [nvarchar](max) NULL,
[meta_description] [nvarchar](max) NULL,
[active] [bit] NOT NULL,
[creation_date] [date] NULL,
CONSTRAINT [PK_Pages]
PRIMARY KEY CLUSTERED ([page_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].[Pages] WITH CHECK
ADD CONSTRAINT [FK_Pages_SubMenu]
FOREIGN KEY([submenu_id]) REFERENCES [dbo].[SubMenu] ([submenu_id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Pages] CHECK CONSTRAINT [FK_Pages_SubMenu]
GO
ALTER TABLE [dbo].[Pages]
ADD CONSTRAINT [DF_Pages_active] DEFAULT ((1)) FOR [active]
GO
You are saying that Problem is I always get multiple records no matter what I do.
The query that you show has top 1 in the very first line, it will always return just one row.
What's wrong with it?
From what I see your SQL query matches what your LINQ query does.
In this case LINQ query cannot possible return more rows than SQL returns.
I have a batch job that synchronizes data between two identical databases using the MERGE statement. Sometimes, I get the following error: cannot insert duplicate key row in object 'dbo.MatchPlayerStatistics' with unique index 'IX_MatchPlayerStatistics_Player'. That does not make sense because IX_MatchPlayerStatistics_Player is not a unique index, and I am able to insert the exact same data manually. If I drop the index, insert the data, then recreate the index, it works fine.
Why does this error occur and how can I prevent it?
More information
The creation script for the table is the following:
CREATE TABLE [dbo].[MatchPlayerStatistics](
[ExternalID] [nvarchar](50) NULL,
[ProviderID] [int] NOT NULL,
[MatchID] [int] NOT NULL,
[PlayerPersonID] [int] NOT NULL,
[TeamID] [int] NOT NULL,
[YellowCards] [smallint] NULL,
[DoubleYellowCards] [smallint] NULL,
[RedCards] [smallint] NULL,
[Fouls] [smallint] NULL,
[Goals] [smallint] NULL,
[PenaltyGoals] [smallint] NULL,
[PenaltiesMissed] [smallint] NULL,
[PenaltiesSaved] [smallint] NULL,
[Shots] [smallint] NULL,
[Attacks] [smallint] NULL,
[Corners] [smallint] NULL,
[Offsides] [smallint] NULL,
[Assists] [smallint] NULL,
[OwnGoals] [smallint] NULL,
[GoalsConcedeed] [smallint] NULL,
[CreatedBy] [int] NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[ModifiedBy] [int] NOT NULL,
[ModifiedOn] [datetime] NOT NULL,
CONSTRAINT [PK_MatchPlayerStatistics] PRIMARY KEY CLUSTERED
(
[ProviderID] ASC,
[MatchID] ASC,
[PlayerPersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_MatchPlayerStatistics_Player] ON [dbo].[MatchPlayerStatistics]
(
[ProviderID] ASC,
[PlayerPersonID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
The MERGE statement is the following:
MERGE MatchPlayerStatistics AS M
USING (
SELECT [ExternalID]
,[ProviderID]
,[MatchID]
,[PlayerPersonID]
,[TeamID]
,[YellowCards]
,[DoubleYellowCards]
,[RedCards]
,[Fouls]
,[Goals]
,[PenaltyGoals]
,[PenaltiesMissed]
,[PenaltiesSaved]
,[Shots]
,[Attacks]
,[Corners]
,[Offsides]
,[Assists]
,[OwnGoals]
,[GoalsConcedeed]
,[CreatedBy]
,[CreatedOn]
,[ModifiedBy]
,[ModifiedOn]
FROM [Replication].MatchPlayerStatistics
WHERE ProviderID = 1
) AS R
ON (M.MatchID = R.MatchID AND M.PlayerPersonID = R.PlayerPersonID AND M.ProviderID = R.ProviderID )
WHEN NOT MATCHED
THEN
INSERT ([ExternalID]
,[ProviderID]
,[MatchID]
,[PlayerPersonID]
,[TeamID]
,[YellowCards]
,[DoubleYellowCards]
,[RedCards]
,[Fouls]
,[Goals]
,[PenaltyGoals]
,[PenaltiesMissed]
,[PenaltiesSaved]
,[Shots]
,[Attacks]
,[Corners]
,[Offsides]
,[Assists]
,[OwnGoals]
,[GoalsConcedeed]
,[CreatedBy]
,[CreatedOn]
,[ModifiedBy]
,[ModifiedOn])
VALUES
( R.[ExternalID]
,R.[ProviderID]
,R.[MatchID]
,R.[PlayerPersonID]
,R.[TeamID]
,R.[YellowCards]
,R.[DoubleYellowCards]
,R.[RedCards]
,R.[Fouls]
,R.[Goals]
,R.[PenaltyGoals]
,R.[PenaltiesMissed]
,R.[PenaltiesSaved]
,R.[Shots]
,R.[Attacks]
,R.[Corners]
,R.[Offsides]
,R.[Assists]
,R.[OwnGoals]
,R.[GoalsConcedeed]
,R.[CreatedBy]
,R.[CreatedOn]
,R.[ModifiedBy]
,R.[ModifiedOn])
WHEN MATCHED
THEN
UPDATE
SET [ExternalID] = R.[ExternalID]
,[ProviderID] = R.[ProviderID]
,[MatchID] = R.[MatchID]
,[PlayerPersonID] = R.[PlayerPersonID]
,[TeamID] = R.[TeamID]
,[YellowCards] = R.[YellowCards]
,[DoubleYellowCards] = R.[DoubleYellowCards]
,[RedCards] = R.[RedCards]
,[Fouls] = R.[Fouls]
,[Goals] = R.[Goals]
,[PenaltyGoals] = R.[PenaltyGoals]
,[PenaltiesMissed] = R.[PenaltiesMissed]
,[PenaltiesSaved] = R.[PenaltiesSaved]
,[Shots] = R.[Shots]
,[Attacks] = R.[Attacks]
,[Corners] = R.[Corners]
,[Offsides] = R.[Offsides]
,[Assists] = R.[Assists]
,[OwnGoals] = R.[OwnGoals]
,[GoalsConcedeed] = R.[GoalsConcedeed]
,[CreatedBy] = R.[CreatedBy]
,[CreatedOn] = R.[CreatedOn]
,[ModifiedBy] = R.[ModifiedBy]
,[ModifiedOn] = R.[ModifiedOn]
WHEN NOT MATCHED BY SOURCE AND M.ProviderID = 1
THEN DELETE;
The [Replication].MatchPlayerStatistics table is an intermediate table that is filled with data from the [dbo].MatchPlayerStatistics table on another copy of the database. The schema for all these tables is the same.
One idea I have is to check and see if there are triggers on the table and if one of them is inserting to another table that has a unique index.
Looking at your code, here is a completely wild guess. You are using IGNORE_DUP_KEY = OFF which is normally only used for unique constraints, so I wonder if it is considering it a unique constraint even without the unique keyword. Try creating the index without that phrase and see what happens.