Temporal Table SYSTEM_TIME Range Not Working - sql-server

I have a temporal table defined as:
CREATE TABLE [dbo].[MyTable](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](200) NOT NULL,
[Description] [varchar](100) NULL,
[CreatedOn] [datetime] NULL,
[LastUpdatedOn] [datetime] NULL,
[SysStartTime] [datetime2](7) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEndTime] [datetime2](7) GENERATED ALWAYS AS ROW END NOT NULL
CONSTRAINT [PK_MyTable] 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],
PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])
) ON [PRIMARY]
WITH
(
SYSTEM_VERSIONING = ON ( HISTORY_TABLE = [dbo].[MyTable_History] )
)
and when I try to do a query like this:
SELECT * FROM MyTable FOR SYSTEM_TIME from '2020-08-18 00:00:00' to '2020-08-18 23:59:59'
I seem to get rows that are not in the range as well. For example,
Name1 Description1 2018-07-05 22:53:36.543 2020-03-17 16:25:44.707 2020-07-22 18:21:03.9662004 9999-12-31 23:59:59.9999999
2020-07-22 is not in the range but why is it showing up?

Related

How do I add system versioning to this table definition with clause?

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))

Group by In SQL query is not working well in my query

I have 3 tables . Orders, OrderLines, BillLines. The primary key of Orders is a FK in the 2 other tables.
I am trying to query the client debit and credit amount.
The Action table just describe the type of the transaction
The Subindex table stores the clients names and ids
CREATE TABLE [dbo].[Orders](
[OrderID] [int] IDENTITY(1,1) NOT NULL,
[Ordertype] [nvarchar](max) NULL,
[Orderdate] [datetime2](7) NOT NULL,
[transactionNo] [int] NOT NULL,
[DocumentNo] [int] NOT NULL,
[ordernote] [nvarchar](max) NULL,
[Profittax] [decimal](18, 2) NOT NULL,
[DescDR] [decimal](18, 2) NULL,
[DescCR] [decimal](18, 2) NULL,
[ActionsID] [smallint] NOT NULL,
[SubIndexesID] [smallint] NULL,
CONSTRAINT [PK_dbo.Orders] PRIMARY KEY CLUSTERED
(
[OrderID] 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
ALTER TABLE [dbo].[Orders] WITH CHECK ADD CONSTRAINT [FK_dbo.Orders_dbo.Actions_ActionsID] FOREIGN KEY([ActionsID])
REFERENCES [dbo].[Actions] ([ActionsID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_dbo.Orders_dbo.Actions_ActionsID]
GO
ALTER TABLE [dbo].[Orders] WITH CHECK ADD CONSTRAINT [FK_dbo.Orders_dbo.SubIndexes_SubIndexesID] FOREIGN KEY([SubIndexesID])
REFERENCES [dbo].[SubIndexes] ([SubIndexesID])
GO
ALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_dbo.Orders_dbo.SubIndexes_SubIndexesID]
GO
CREATE TABLE [dbo].[Orderlines](
[OrderlinesID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NOT NULL,
[Qin] [smallint] NOT NULL,
[Qout] [smallint] NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
[currency] [nvarchar](max) NULL,
[Discount] [decimal](18, 2) NOT NULL,
[VAT] [decimal](18, 2) NOT NULL,
[ItemsID] [smallint] NOT NULL,
[Total] [decimal](18, 2) NOT NULL,
[Vatvalue] [decimal](18, 2) NOT NULL,
[Net] [decimal](18, 2) NOT NULL,
CONSTRAINT [PK_dbo.Orderlines] PRIMARY KEY CLUSTERED
(
[OrderlinesID] 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
ALTER TABLE [dbo].[Orderlines] ADD DEFAULT ((0)) FOR [Total]
GO
ALTER TABLE [dbo].[Orderlines] ADD DEFAULT ((0)) FOR [Vatvalue]
GO
ALTER TABLE [dbo].[Orderlines] ADD DEFAULT ((0)) FOR [Net]
GO
ALTER TABLE [dbo].[Orderlines] WITH CHECK ADD CONSTRAINT [FK_dbo.Orderlines_dbo.Items_ItemsID] FOREIGN KEY([ItemsID])
REFERENCES [dbo].[Items] ([ItemsID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Orderlines] CHECK CONSTRAINT [FK_dbo.Orderlines_dbo.Items_ItemsID]
GO
ALTER TABLE [dbo].[Orderlines] WITH CHECK ADD CONSTRAINT [FK_dbo.Orderlines_dbo.Orders_OrderID] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Orderlines] CHECK CONSTRAINT [FK_dbo.Orderlines_dbo.Orders_OrderID]
GO
CREATE TABLE [dbo].[BillLines](
[BillLinesID] [int] IDENTITY(1,1) NOT NULL,
[VALIN] [decimal](18, 2) NULL,
[VALOut] [decimal](18, 2) NULL,
[OrderID] [int] NOT NULL,
[SubIndexesID] [smallint] NULL,
CONSTRAINT [PK_dbo.BillLines] PRIMARY KEY CLUSTERED
(
[BillLinesID] 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].[BillLines] WITH CHECK ADD CONSTRAINT [FK_dbo.BillLines_dbo.Orders_OrderID] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BillLines] CHECK CONSTRAINT [FK_dbo.BillLines_dbo.Orders_OrderID]
GO
ALTER TABLE [dbo].[BillLines] WITH CHECK ADD CONSTRAINT [FK_dbo.BillLines_dbo.SubIndexes_SubIndexesID] FOREIGN KEY([SubIndexesID])
REFERENCES [dbo].[SubIndexes] ([SubIndexesID])
GO
ALTER TABLE [dbo].[BillLines] CHECK CONSTRAINT [FK_dbo.BillLines_dbo.SubIndexes_SubIndexesID]
GO
CREATE TABLE [dbo].[Actions](
[ActionsID] [smallint] IDENTITY(1,1) NOT NULL,
[Actionname] [nvarchar](4000) NOT NULL,
CONSTRAINT [PK_dbo.Actions] PRIMARY KEY CLUSTERED
(
[ActionsID] 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
CREATE TABLE [dbo].[SubIndexes](
[SubIndexesID] [smallint] IDENTITY(1,1) NOT NULL,
[Subname] [nvarchar](max) NULL,
[AccountIndexID] [smallint] NOT NULL,
[Contacttype] [nvarchar](max) NULL,
[phones] [nvarchar](max) NULL,
[fax] [nvarchar](max) NULL,
[email] [nvarchar](max) NULL,
[address] [nvarchar](max) NULL,
[zip] [nvarchar](max) NULL,
[Website] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.SubIndexes] PRIMARY KEY CLUSTERED
(
[SubIndexesID] 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
ALTER TABLE [dbo].[SubIndexes] WITH CHECK ADD CONSTRAINT [FK_dbo.SubIndexes_dbo.AccountIndexes_AccountIndexID] FOREIGN KEY([AccountIndexID])
REFERENCES [dbo].[AccountIndexes] ([AccountIndexID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SubIndexes] CHECK CONSTRAINT [FK_dbo.SubIndexes_dbo.AccountIndexes_AccountIndexID]
GO
My Query is
select distinct
o.OrderID ,
s.Subname as subindexname,
o.SubIndexesID as Subindex ,
sum(ol.Qout * (ol.Price - ol.Discount)* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALOut) -iif(o.ActionsID between 3 and 4, o.DescDR+o.DescCR,0) as Debit ,
sum(ol.Qin * (ol.Price - ol.Discount )* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALIN)-iif(o.ActionsID not between 3 and 4,o.DescCR + o.DescDR,0) as Credit
from Orders o
inner join
Orderlines ol on o.OrderID = ol.OrderID
inner join
BillLines bl on o.OrderID = bl.OrderID
inner join
SubIndexes s on o.SubIndexesID= s.SubIndexesID
group by o.OrderID,
o.ActionsID,
o.SubIndexesID,
o.DescCR,
o.DescDR,
ol.Qout,
ol.Qin,
s.Subname,
s.SubIndexesID,
ol.VAT,
ol.Price,
ol.Discount
having o.ActionsID=2
or o.ActionsID=3
or o.ActionsID=4
or o.ActionsID=5
I want to show the debit and the credit in one row even I have multiple orderlines for one order.
It is necessary to include all cols in Group-by in Select as well:
select distinct
o.OrderID ,
s.Subname as subindexname,
o.SubIndexesID as Subindex ,
o.ActionsID,
o.DescCR,
o.DescDR,
ol.Qout,
ol.Qin,
s.Subname,
s.SubIndexesID,
ol.VAT,
ol.Price,
ol.Discount
sum(ol.Qout * (ol.Price - ol.Discount)* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALOut) -iif(o.ActionsID between 3 and 4, o.DescDR+o.DescCR,0) as Debit ,
sum(ol.Qin * (ol.Price - ol.Discount )* (1+(ol.VAT/100)-(o.Profittax/100))+ bl.VALIN)-iif(o.ActionsID not between 3 and 4,o.DescCR + o.DescDR,0) as Credit
from Orders o
inner join
Orderlines ol on o.OrderID = ol.OrderID
inner join
BillLines bl on o.OrderID = bl.OrderID
inner join
SubIndexes s on o.SubIndexesID= s.SubIndexesID
group by o.OrderID,
o.ActionsID,
o.SubIndexesID,
o.DescCR,
o.DescDR,
ol.Qout,
ol.Qin,
s.Subname,
s.SubIndexesID,
ol.VAT,
ol.Price,
ol.Discount
having o.ActionsID=2
or o.ActionsID=3
or o.ActionsID=4
or o.ActionsID=5

Getting the first occurence of rows

I have a table created by the following t-sql statement:
CREATE TABLE [Core].[PriceHistory](
[PriceHistoryId] [bigint] IDENTITY(1,1) NOT NULL,
[SourceId] [tinyint] NOT NULL,
[SymbolId] [smallint] NOT NULL,
[Ask] [real] NOT NULL,
[Bid] [real] NOT NULL,
[TickTime] [bigint] NOT NULL,
[ModifiedDate] [datetime2](3) NOT NULL,
[Direction] [tinyint] NULL,
CONSTRAINT [PK_PriceHistory] PRIMARY KEY CLUSTERED
(
[PriceHistoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Let's say I have a list of SymbolIds, for example (1, 2, 3).
I want to get the first rows foreach SymbolId having ModifiedDate is > than '2016-04-01 00:00:00'
SELECT *
FROM (
SELECT DENSE_RANK() OVER (
PARTITION BY SymbolId ORDER BY ModifiedDate
) RNK
,*
FROM PriceHistory
WHERE ModifiedDate > '2014-04-01 00:00:00'
) T
WHERE RNK = 1

SQL Server what indexes to create

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);

Querying 3 tables where I'm looking for non-matches

I have three tables: LitHold, LitHoldDetails and EmailTemplate. The definitions are as follows.
CREATE TABLE [dbo].[LitHold](
[LitholdID] [int] IDENTITY(1,1) NOT NULL,
[LitHoldStatusID] [tinyint] NOT NULL,
[EmailReminderID] [tinyint] NULL,
[ApprovedDate] [datetime] NULL,
[TerminatedDate] [datetime] NULL,
CONSTRAINT [PK_Lithold] PRIMARY KEY CLUSTERED
(
[LitholdID] 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].[LitHoldDetails](
[LitHoldDetailsID] [int] IDENTITY(1,1) NOT NULL,
[LitholdID] [int] NOT NULL,
[VersionID] [int] NOT NULL,
[Description] [varchar](300) NULL,
[ResAttorneyID] [varchar](10) NOT NULL,
[Comments] [varchar](1000) NULL,
[HoldStartDate] [datetime] NULL,
[HoldEndDate] [datetime] NULL,
[CreatedDate] [datetime] NOT NULL,
[CreatedByLogin] [varchar](10) NULL,
CONSTRAINT [PK_LitholdDetails] PRIMARY KEY CLUSTERED
(
[LitHoldDetailsID] 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].[EmailTemplate](
[TemplateID] [int] IDENTITY(1,1) NOT NULL,
[LitHoldDetailsID] [int] NOT NULL,
[From] [varchar](50) NULL,
[To] [varchar](2000) NULL,
[CC] [varchar](500) NULL,
[BCC] [varchar](500) NULL,
[Subject] [nvarchar](200) NULL,
[MessageBody] [nvarchar](max) NULL,
[SendDate] [datetime] NULL,
[IsDefault] [bit] NOT NULL,
CONSTRAINT [PK_EmailTemplate] PRIMARY KEY CLUSTERED
(
[TemplateID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
For each LitHold, there can be multiple LitHoldDetails. For each LitHoldDetail, there should be one EmailTemplate. I recently found that some LitHoldDetails do NOT have EmailTemplates. We're still working in development on this project, so this isn't a big deal. However, we want to get the EmailTemplate data into the database. The situation is that for each LitHold, there is at least one LitHoldDetail that has an EmailTemplate. I would like to duplicate this EmailTemplate data for all the LitHoldDetails that a) have the same LitHoldID and b) do not have an EmailTemplate. One of the approaches I've tried is:
insert into EmailTemplate
(LitHoldDetailsID, [From], [To], CC, BCC, Subject, MessageBody, SendDate, IsDefault)
(select (select top 1 LitHoldDetailsID from LitHoldDetails where LitholdID = d.LitholdID and LitHoldDetailsID <> e.LitHoldDetailsID), [To], CC, BCC, Subject, MessageBody, SendDate, IsDefault from
EmailTemplate e inner join LitHoldDetails d on e.LitHoldDetailsID = d.LitHoldDetailsID)
but this gets me multiple rows for some LitHoldDetails, with different EmailTemplate data, and some rows where LitHoldDetails is NULL. How can I accomplish this? I'm using SQL Server 2008.
Try inserting this:
SELECT lhd.LitHoldDetailsID, CloneEmailTemplate.[From], ...
FROM LitHoldDetails lhd
CROSS APPLY (SELECT TOP 1 et.*
FROM EmailTemplate et
JOIN LitHoldDetails lhd2 ON lhd2.LitHoldDetailsID = et.LitHoldDetailsID
WHERE lhd2.LitHoldID = lhd.LitHoldID
) AS CloneEmailTemplate
WHERE NOT EXISTS (SELECT 1
FROM EmailTemplate et2
WHERE et2.LitHoldDetailsID = lhd.LitHoldDetailsID
)

Resources