I have a simple table:
CREATE TABLE DocModHistory
[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[DocID] [int] NOT NULL,
[BranchID] [int] NOT NULL,
[UserID] [int] NOT NULL,
[InsDate] [datetime] NOT NULL,
[Type] [int] NOT NULL,
CONSTRAINT [PK_DocModHistory] 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]
and I have two select queries:
SELECT dh.BranchID, MAX(dh.ID) as MaxID FROM DocModHistory dh WHERE dh.UserID = #p_UserID GROUP BY dh.BranchID
and
SELECT dh.DocID, MAX(dh.ID) as MaxID FROM DocModHistory dh WHERE dh.UserID = #p_UserID GROUP BY dh.DocID
Could you tell me please what indexes should I create?
Shall I create individual indexes for UserID, BranchID, DocID, or do I need multi-column indexes?
Thank you!
Create an index for UserID with Included columns BranchID, ID and DocID
So something like
CREATE INDEX IX_UserID ON DocModHistory (UserID) INCLUDE (BranchID, ID ,DocID);
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))
My INSERT statement fails while it is trying to add a new record into an empty table (Attribute) (no record yet).
I am surprised by the error raised by the system:
Violation of UNIQUE KEY constraint 'CK_Attribute_Name_IDproject'. Cannot insert duplicate key in object 'dbo.Attribute'. The duplicate key value is (dummy, 55).
The creation script for this table looks like
CREATE TABLE [dbo].[Attribute](
[ID] [int] IDENTITY(1,1) NOT NULL,
[IDproject] [int] NOT NULL,
[IDtype] [int] NOT NULL,
[IDgroup] [int] NOT NULL,
[name] [varchar](50) NOT NULL,
[color] [int] NULL,
[protected] [tinyint] NULL,
[datemodified] [datetime] NOT NULL,
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 [CK_Attribute_Name_IDproject] UNIQUE NONCLUSTERED
(
[name] ASC,
[IDproject] 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
I skiped foreign keys references and default values which does not seem of interest in this context.
The UNIQUE constraint applies to [name] and [IDproject].
When running the following statement
SELECT *
FROM [dbo].[Attribute]
GO
SELECT *
FROM [dbo].[Project]
GO
I get the results
(0 row(s) affected)
(2 row(s) affected)
The first result indicats the Attribute Table is empty
The second that there are 2 Projects
then running the following INSERT in table Attribute it failed with the above mentioned UNIQUE CONSTRAINT error
INSERT INTO [dbo].[Attribute] ([IDproject], [name], [IDtype], [IDgroup], [color], [protected], [datemodified])
SELECT DISTINCT
p.[ID],'dummy',t.[ID],g.[ID],-1,0,getdate()
FROM [dbo].[Project] p
INNER JOIN [dbo].[Group] g ON g.[name]='none' AND g.[IDproject] = p.[ID]
INNER JOIN [dbo].[AttributeType] t ON t.[format]='text' AND g.[IDproject] = p.[ID]
WHERE p.[name]='TESTPROJ'
GO
How can i get such an error on an empty table ?
I have found the solution myself: the derived SELECT returns 2 records with 'dummy' due to a duplicate INTO one of table, AttributeType, with which INNER JOIN is performed.
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 need to create a stored procedure transaction that will pull data from two tables and create a random integer to populate a third table (dbo.patient_address).
I want the following, but I am having a hard time understanding how to script this as a stored procedure.
dbo.address AddressID = dbo.patient_address AddressID,
dbo.patient PatientID = dbo.patient_address PatientID,
RAND is an integer between 1-3 (see dbo.addresstype) = dbo.patient_address AddressTypeID
Below are create statements of all of these tables.
ADDRESS TABLE - 30000 rows in place (complete data set)
CREATE TABLE [dbo].[ADDRESS](
[AddressID] [int] NOT NULL,
[StreetAddress] [varchar](50) NULL,
[City] [varchar](50) NULL,
[State] [varchar](50) NULL,
[PostalCode] [varchar](50) NULL,
CONSTRAINT [ADDRESS_PK] PRIMARY KEY CLUSTERED
(
[AddressID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
PATIENT TABLE - 30000 rows in place (complete data set)
CREATE TABLE [dbo].[PATIENT](
[PatientID] [int] NOT NULL,
[PatientFName] [varchar](50) NOT NULL,
[PatientLName] [varchar](50) NOT NULL,
[GenderID] [int] NOT NULL,
[DateOfBirth] [date] NOT NULL,
CONSTRAINT [PATIENT_PK] PRIMARY KEY CLUSTERED
(
[PatientID] 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
ADDRESS TYPE - 3 choices (home, billing, work) – integer between 1 - 3
CREATE TABLE [dbo].[ADDRESS_TYPE](
[AddressTypeID] [int] NOT NULL,
[AddressTypeName] [varchar](10) NOT NULL,
[AddressTypeDescr] [varchar](10) NULL,
CONSTRAINT [ADDRESS_TYPE_PK] PRIMARY KEY CLUSTERED
(
[AddressTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
INSERT INTO [dbo].[ADDRESS_TYPE]
([AddressTypeID],[AddressTypeName],[AddressTypeDescr])
Values ('1','Home','Home'), ('2','Bill','Billing'), ('3','Work','Work')
This is the final table that I want to populate from all of the above tables using a stored procedure transaction.
CREATE TABLE [dbo].[PATIENT_ADDRESS](
[PatientID] [int] NOT NULL,
[AddressID] [int] NOT NULL,
[AddressTypeID] [int] NULL,
CONSTRAINT [PATIENT_ADDRESS_PK] PRIMARY KEY CLUSTERED
(
[PatientID] ASC,
[AddressID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Try this:
INSERT INTO PATIENT_ADDRESS
SELECT PatientID, AddressID,
CONVERT(INT,(ABS(CHECKSUM(NEWID())/2148000000.))*3)+1 AS AddressTypeID
FROM (
SELECT PatientID, ROW_NUMBER() OVER (ORDER BY PatientID) AS RowNum
FROM dbo.PATIENT
) x
INNER JOIN (
SELECT AddressID, ROW_NUMBER() OVER (ORDER BY AddressID) AS RowNum
FROM dbo.ADDRESS
) y ON x.RowNum = y.RowNum
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.