Computed column slows down query performance in SQL Server 2012 - sql-server

In my select statement, the column DisplayStatus is a computed column that significantly slows down the performance.
I tried to make it PERSISTENT but it tells me that table need to be dropped and recreated again. I cannot do that, I am not the owner of those tables.
Scalar function (pretty complex) is responsible for computed column.
My select statement:
declare
#EffDateFrom datetime ='2017-02-01',
#EffDateTo datetime ='2017-08-28'
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#Data') IS NOT NULL
DROP TABLE #Data
CREATE TABLE #Data
(
QuoteID int NOT NULL,
[EffectiveDate] [datetime] NULL,
[Submitted] [int] NULL,
[Quoted] [int] NULL,
[Bound] [int] NULL,
[Exonerated] [int] NULL,
[ProducerLocationId] [int] NULL,
[ProducerName] [varchar](300) NULL,
[BusinessType] [varchar](50) NULL,
[DisplayStatus] [varchar](50) NULL, --This is the problem
[Agent] [varchar] (50) NULL,
[ProducerContactGuid] uniqueidentifier NULL
)
INSERT INTO #Data
SELECT
tblQuotes.QuoteID,
tblQuotes.EffectiveDate,
CASE
WHEN lstQuoteStatus.QuoteStatusID >= 1
THEN 1
ELSE 0
END AS Submitted,
CASE
WHEN lstQuoteStatus.QuoteStatusID = 2 OR
lstQuoteStatus.QuoteStatusID = 3 OR
lstQuoteStatus.QuoteStatusID = 202
THEN 1
ELSE 0
END AS Quoted,
CASE WHEN lstQuoteStatus.Bound = 1 THEN 1 ELSE 0 END AS Bound,
CASE WHEN lstQuoteStatus.QuoteStatusID = 3 THEN 1 ELSE 0 END AS Exonareted,
tblQuotes.ProducerLocationID,
P.Name + ' / '+ P.City as [ProducerName],
CASE
WHEN tblQuotes.PolicyTypeID = 1 THEN 'New Business'
WHEN tblQuotes.PolicyTypeID = 3 THEN 'Rewrite'
END AS BusinessType,
tblQuotes.DisplayStatus, -------------This is the problem
tblProducerContacts.FName +' '+ tblProducerContacts.LName as Agent,
tblProducerContacts.ProducerContactGUID
FROM
tblQuotes
INNER JOIN
lstQuoteStatus ON tblQuotes.QuoteStatusID = lstQuoteStatus.QuoteStatusID
INNER JOIN
tblProducerLocations P ON P.ProducerLocationID = tblQuotes.ProducerLocationID
INNER JOIN
tblProducerContacts ON dbo.tblQuotes.ProducerContactGuid = tblProducerContacts.ProducerContactGUID
WHERE
tblQuotes.EffectiveDate >= #EffDateFrom
AND tblQuotes.EffectiveDate <= #EffDateTo
AND dbo.tblQuotes.LineGUID = '6E00868B-FFC3-4CA0-876F-CC258F1ED22D'--Surety
AND tblQuotes.OriginalQuoteGUID IS NULL
SELECT * FROM #Data
Is any other workaround to bring this column without slowing down the performance?
Execution Plan:

Related

SQL column and datetime field not updating when using case

I have a dimension table updating from a stage table the 1st condition is that dim.dim_patient.Determination_Code=patient.Determination_Code after which other fields should update if there is a difference spotted in any of the fields below. It is not picking up the changes and when it does update the field it doesn't update the corresponding dss_update_time field.
drop table #dim_patient
CREATE TABLE #dim_patient(
[id] [varchar](20) NULL,
[episode] [int] NULL,
[Status_date] [date] NULL,
[Determination_Code] [varchar](40) NULL,
[Determination] [varchar](40) NULL,
[Status_Code] [varchar](40) NULL,
[Status_Value] [varchar](40) NULL,
[Days] [int] NULL,
[RTP_Date] [varchar](500) NULL,
[PET_Date] [date] NULL,
[dss_create_time] [datetime] NULL,
[dss_update_time] [datetime] NULL
)
----------------------------------------------------------------------------------------------------------
--primary keys are patid and episode number
--when Determination_Code is the same status_date should remain the same
--every other record should update
-------------------------------------------------------------------------------------------------
INSERT INTO #dim_patient VALUES
('1435','4','2019-08-01','2','Not Ready',NULL, NULL,NULL,NULL,NULL ,'2022-09-08 13:49:20.660','2022-09-08 13:49:20.660')
,('1435','5','2021-10-12','1','Ready ', 'Yes','Yes','50','2022-11-02',NULL,'2022-09-08 13:49:20.660','2022-11-08 17:04:39.233')
select * from #dim_patient
UPDATE [dim].[dim_patient] WITH ( TABLOCK )
SET
----Status_date = patient.Status_date
, Determination_Code = patient.Determination_Code
, Determination = patient.Determination
, Status_Code = patient.Status_Code
, Status_Value = patient.Status_Value
, Days = patient.Days
, RTP_Date = patient.RTP_Date
, PET_Date = patient.PET_Date
,dss_update_time =
---= getdate()
CASE WHEN dim_patient.Status_Code <> patient.Status_Code
THEN getdate()
WHEN dim_patient.Days <> patient.Days
THEN getdate()
WHEN dim_patient.RTP_Date <> patient.RTP_Date
THEN getdate()
WHEN dim_patient.PET_Date <> patient.PET_Date
THEN getdate()
ELSE dim.dim_patient.dss_update_time
END
FROM [stage].[patient] patient
JOIN dim.dim_patient
ON dim.dim_patient.id=patient.id
AND dim.dim_patient.episode=patient.episode
where dim.dim_patient.Determination_Code=patient.Determination_Code
AND (
( dim.dim_patient.Status_Code <>patient.Status_Code)
OR ( dim.dim_patient.Days <> patient.Days)
OR ( dim.dim_patient.RTP_Date <> patient.RTP_Date)
OR (dim.dim_patient.PET_Date <> patient.PET_Date)
)

After adding Feature Name and Feature Value query takes more than 5 minutes

I work on SQL Server 2014 and my issue occurred after displaying Feature Name and Feature Value separated by $.
When executing the query below after adding Feature Name and Feature Value with stuff it became very slow.
How to enhance it?
Before adding the two stuff statements it took 28 seconds to display 750 thousand records. Now as below script and after adding two stuff statements take 5 minutes.
Script below give me expected result but issue is performance is very slow.
So can I do separate Feature Name and Feature Value to make it faster? Separated by $ if possible.
My script:
IF OBJECT_ID('[dbo].[gen]') IS NOT NULL
DROP TABLE [dbo].[gen]
IF OBJECT_ID('[dbo].[PartAttributes]') IS NOT NULL
DROP TABLE [dbo].[PartAttributes]
IF OBJECT_ID('dbo.core_datadefinition_Detailes') IS NOT NULL
DROP TABLE core_datadefinition_Detailes
CREATE TABLE core_datadefinition_Detailes
(
[ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[ColumnName] [nvarchar](500) NOT NULL,
[ColumnNumber] [int] NOT NULL,
CONSTRAINT [PK_Core_DataDefinition_Details]
PRIMARY KEY CLUSTERED ([ID] ASC)
)
INSERT INTO core_datadefinition_Detailes([ColumnNumber],[ColumnName])
VALUES (202503, 'Product Shape Type'),
(1501170111, 'Type'),
(202504, 'Package Family')
CREATE TABLE [dbo].[gen]
(
[TradeCodeControlID] [int] IDENTITY(1,1) NOT NULL,
[CodeTypeID] [int] NULL,
[RevisionID] [bigint] NULL,
[Code] [varchar](20) NULL,
[ZPLID] [int] NULL,
[ZfeatureKey] [bigint] NULL,
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[gen] ON
INSERT INTO [dbo].[gen] ([TradeCodeControlID], [CodeTypeID],[RevisionID], [Code], [ZPLID], [ZfeatureKey])
VALUES (7565, 849774, 307683692, N'8541100050', 4239, 202503)
INSERT INTO [dbo].[gen] ([TradeCodeControlID], [CodeTypeID],[RevisionID], [Code], [ZPLID], [ZfeatureKey])
VALUES (7566, 849774, 307683692, N'8541100050', 4239, 202504)
INSERT INTO [dbo].[gen] ([TradeCodeControlID], [CodeTypeID],[RevisionID], [Code], [ZPLID], [ZfeatureKey])
VALUES (7567, 849774, 307683692, N'8541100050', 4239, 1501170111)
SET IDENTITY_INSERT [dbo].[gen] OFF
CREATE TABLE [dbo].[PartAttributes]
(
[PartID] [int] NOT NULL,
[ZfeatureKey] [bigint] NULL,
[AcceptedValuesOption_Value] [float] NULL,
[FeatureValue] [nvarchar](500) NOT NULL
) ON [PRIMARY]
GO
INSERT INTO [dbo].[PartAttributes] ([PartID], [ZfeatureKey], [FeatureValue])
VALUES (413989, 202503, N'Discrete')
INSERT INTO [dbo].[PartAttributes] ([PartID], [ZfeatureKey], [FeatureValue])
VALUES (413989, 1501170111, N'Zener')
INSERT INTO [dbo].[PartAttributes] ([PartID], [ZfeatureKey], [FeatureValue])
VALUES (413989, 202504, N'SOT')
SELECT
PartID, Code, Co.CodeTypeID, Co.RevisionID, Co.ZPLID,
COUNT(1) AS ConCount,
STUFF((SELECT '$' + CAST(CP.ColumnName AS VARCHAR(300)) AS [text()]
FROM
(SELECT DISTINCT
d.ColumnName, C.codeTypeId, C.Code, C.ZfeatureKey
FROM gen C
INNER JOIN core_datadefinitiondetails d WITH (NOLOCK) ON C.ZfeatureKey = d.columnnumber
INNER JOIN PartAttributes P ON P.partid = PM.partid) CP
WHERE CP.codeTypeId = Co.codeTypeId AND CP.Code = Co.Code
ORDER BY CP.ZfeatureKey
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS FeatureName,
STUFF((SELECT '$' + CAST(CP2.FeatureValue AS VARCHAR(300)) AS [text()]
FROM
(SELECT DISTINCT
P.FeatureValue, C2.codeTypeId, C2.Code, C2.ZfeatureKey
FROM gen C2
INNER JOIN PartAttributes P ON C2.ZfeatureKey = P.ZfeatureKey) CP2
WHERE CP2.codeTypeId = Co.codeTypeId AND CP2.Code = Co.Code
ORDER BY CP2.ZfeatureKey
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS FeatureValue
FROM
PartAttributes PM
INNER JOIN
gen Co ON Co.ZfeatureKey = PM.ZfeatureKey
GROUP BY
PartID, Code, Co.CodeTypeID, Co.RevisionID, Co.ZPLID
Final result:
final result after add two stuff

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMITS

I have the following error when I run a stored procedure in SQL:
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.
What does this mean? How could I solve it?
Thank you very much.
/****** Object: StoredProcedure [SingleDirectory].[SPTADIR_EntityIdentification] Script Date: 26/04/2021 9:37:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [SingleDirectory].[SPTADIR_EntityIdentification]
-- Add the parameters for the stored procedure here
#xmlEntity nvarchar(MAX) = NULL
AS
SET XACT_ABORT ON
BEGIN TRAN
BEGIN TRY
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE
#handle int,
#currentDateTime datetime
-- =============================================
--- Protection Against Concurrent Executions
-- =============================================
DECLARE #RC INT
DECLARE #message VARCHAR(500)
SELECT #message = CONVERT(VARCHAR(30), GETDATE(), 121) + ': Try to obtain a lock ..'
--RAISERROR(#message, 0, 1) WITH NOWAIT;
EXEC #RC = sp_getapplock
#Resource = '[SingleDirectory].[SPTADIR_EntityIdentification]',
#LockMode = 'Exclusive',
#LockOwner = 'Transaction',
#LockTimeout = 6000 -- 0.1 minute
IF #RC < 0
BEGIN
IF ##TRANCOUNT > 0 ROLLBACK TRAN;
SELECT #message = CONVERT(VARCHAR(30), GETDATE(), 121) + ': Sorry, could not obtain a lock within the timeout period, return code was ' + CONVERT(VARCHAR(30), #RC) + '.'
--RAISERROR(#message, 0, 1) WITH NOWAIT;
RETURN #RC
END
ELSE
BEGIN
SELECT #message = CONVERT(VARCHAR(30), GETDATE(), 121) + ': AppLock obtained ..'
--RAISERROR(#message, 0, 1) WITH NOWAIT;
END
-- ******************************
-- 1.- Creates tables
-- ******************************
-- TADIR_Entity identification
CREATE TABLE [#tmpEntity] (
[EntityId] [int] NULL,
[EntityType] [int] NOT NULL,
[VendorId] [int] NULL,
[ProviderEntityId] [varchar](100) COLLATE Latin1_General_100_CI_AS_SC NULL,
[FiscalId] [varchar](15) COLLATE Latin1_General_100_CI_AS_SC NULL,
[BusinessName] [nvarchar](150) COLLATE Latin1_General_100_CI_AS_SC NULL,
[AddressName] [varchar](100) COLLATE Latin1_General_100_CI_AS_SC NULL,
[PostalCode] [varchar](10) COLLATE Latin1_General_100_CI_AS_SC NULL,
[CityName] [varchar](50) COLLATE Latin1_General_100_CI_AS_SC NULL,
[CountryDescr] [varchar](50) COLLATE Latin1_General_100_CI_AS_SC NULL,
[StateId] [int] NULL,
[PhoneNbr] [varchar](20) COLLATE Latin1_General_100_CI_AS_SC NULL,
[SystemId] [int] NULL,
[ActiveFlag] [bit] NOT NULL,
[ISO2Value] [varchar](2) COLLATE Latin1_General_100_CI_AS_SC NULL,
[ISO3Value] [varchar](3) COLLATE Latin1_General_100_CI_AS_SC NULL,
[InfoBusinessTypeId] [int] NULL
)
CREATE CLUSTERED INDEX INDEXEntityId ON [#tmpEntity] (EntityId)
CREATE NONCLUSTERED INDEX INDEXProviderEntityId ON [#tmpEntity] (ISO2Value, ProviderEntityId, EntityId)
CREATE NONCLUSTERED INDEX INDEXFiscalId ON [#tmpEntity] (ISO2Value, FiscalId, EntityId)
-- New TADIR_Entity
CREATE TABLE [#tmpEntityInserted] (
[EntityId] [int] NULL,
[VendorId] [int] NULL,
[ProviderEntityId] [varchar](100) COLLATE Latin1_General_100_CI_AS_SC NULL
)
CREATE CLUSTERED INDEX INDEXProviderEntityId ON [#tmpEntityInserted] (VendorId, ProviderEntityId)
-- TADIR_EntityIDs
CREATE TABLE [#tmpEntityIDs] (
[EntityId] [int] NULL,
[VendorId] [int] NULL,
[ProviderEntityId] [varchar](100) COLLATE Latin1_General_100_CI_AS_SC NULL,
[IDType] [tinyint] NULL,
[IdentificationValue] [varchar](50) COLLATE Latin1_General_100_CI_AS_SC NULL
)
CREATE NONCLUSTERED INDEX INDEXProviderEntityId ON [#tmpEntityIDs] (VendorId, ProviderEntityId)
CREATE NONCLUSTERED INDEX INDEXEntityId ON [#tmpEntityIDs] (EntityId, IDType)
-- ******************************
-- 2.- Parses XML and inserts into [#tmpEntity] and [#tmpEntityIDs]
-- ******************************
-- XML
CREATE TABLE [#tmpEntityXml] (
[EntityId] [int] NULL,
[EntityType] [int] NOT NULL,
[VendorId] [int] NULL,
[ProviderEntityId] [varchar](100) COLLATE Latin1_General_100_CI_AS_SC NULL,
[FiscalId] [varchar](15) COLLATE Latin1_General_100_CI_AS_SC NULL,
[BusinessName] [nvarchar](150) COLLATE Latin1_General_100_CI_AS_SC NULL,
[AddressName] [varchar](100) COLLATE Latin1_General_100_CI_AS_SC NULL,
[PostalCode] [varchar](10) COLLATE Latin1_General_100_CI_AS_SC NULL,
[CityName] [varchar](50) COLLATE Latin1_General_100_CI_AS_SC NULL,
[CountryDescr] [varchar](50) COLLATE Latin1_General_100_CI_AS_SC NULL,
[StateId] [int] NULL,
[PhoneNbr] [varchar](20) COLLATE Latin1_General_100_CI_AS_SC NULL,
[SystemId] [int] NULL,
[ActiveFlag] [bit] NOT NULL,
[ISO2Value] [varchar](2) COLLATE Latin1_General_100_CI_AS_SC NULL,
[ISO3Value] [varchar](3) COLLATE Latin1_General_100_CI_AS_SC NULL,
[InfoBusinessTypeId] [int] NULL,
[IDType] [tinyint] NULL,
[IdentificationValue] [varchar](50) COLLATE Latin1_General_100_CI_AS_SC NULL
)
exec sp_xml_preparedocument #handle OUTPUT, #xmlEntity
INSERT INTO [#tmpEntityXml] (
[EntityId],
[EntityType],
[VendorId],
[ProviderEntityId],
[FiscalId],
[BusinessName],
[AddressName],
[PostalCode],
[CityName],
[CountryDescr],
[StateId],
[PhoneNbr],
[SystemId],
[ActiveFlag],
[ISO2Value],
[ISO3Value],
[InfoBusinessTypeId],
[IDType],
[IdentificationValue])
SELECT (CASE WHEN EntityId = 0 THEN NULL ELSE EntityId END) AS EntityId,
EntityType,
(CASE WHEN VendorId = 0 THEN NULL ELSE VendorId END) AS VendorId,
(CASE WHEN ProviderEntityId IS NULL THEN NULL ELSE ProviderEntityId END) AS ProviderEntityId,
FiscalId,
BusinessName,
AddressName,
PostalCode,
CityName,
CountryDescr,
(CASE WHEN StateId = 0 THEN NULL ELSE StateId END) AS StateId,
PhoneNbr,
(CASE WHEN SystemId = 0 THEN NULL ELSE SystemId END) AS SystemId,
ActiveFlag,
ISO2Value,
ISO3Value,
(CASE WHEN InfoBusinessTypeId = 0 THEN NULL ELSE InfoBusinessTypeId END) AS InfoBusinessTypeId,
(CASE WHEN IDType = 0 THEN NULL ELSE IDType END) AS IDType,
IdentificationValue
FROM OPENXML (#handle, 'ArrayOfIdentificationEntity/IdentificationEntity',3)
WITH (
EntityId int 'EntityId',
EntityType int 'EntityType',
VendorId int 'VendorId',
ProviderEntityId varchar(100) 'ProviderEntityId',
FiscalId varchar(15) 'FiscalId',
BusinessName nvarchar(150) 'BusinessName',
AddressName varchar(100) 'AddressName',
PostalCode varchar(10) 'PostalCode',
CityName varchar(50) 'CityName',
CountryDescr varchar(50) 'CountryDescr',
StateId int 'StateId',
PhoneNbr varchar(20) 'PhoneNbr',
SystemId int 'SystemId',
ActiveFlag bit 'ActiveFlag',
ISO2Value varchar(2) 'ISO2Value',
ISO3Value varchar(3) 'ISO3Value',
InfoBusinessTypeId int 'InfoBusinessTypeId',
IDType tinyint 'IDType',
IdentificationValue varchar(50) 'IdentificationValue') AS fbEntity
EXEC sp_xml_removedocument #handle
UPDATE [#tmpEntityXml]
SET EntityId = [SingleDirectory].[TADIR_Entity].EntityId
FROM [SingleDirectory].[TADIR_Entity]
INNER JOIN [#tmpEntityXml]
ON ([SingleDirectory].[TADIR_Entity].[VendorId] = [#tmpEntityXml].[VendorId]
AND [SingleDirectory].[TADIR_Entity].[ProviderEntityId] = [#tmpEntityXml].[ProviderEntityId] AND [SingleDirectory].[TADIR_Entity].EntityType = [#tmpEntityXml].EntityType)
UPDATE [#tmpEntityXml]
SET EntityId = [SingleDirectory].[TADIR_Entity].EntityId
FROM [SingleDirectory].[TADIR_Entity]
INNER JOIN [#tmpEntityXml]
ON ([SingleDirectory].[TADIR_Entity].[VendorId] = [#tmpEntityXml].[VendorId]
AND [SingleDirectory].[TADIR_Entity].FiscalId = [#tmpEntityXml].FiscalId AND [SingleDirectory].[TADIR_Entity].EntityType = [#tmpEntityXml].EntityType)
-- Inserts tmpEntity
INSERT INTO [#tmpEntity]
([EntityId], [EntityType], [VendorId], [ProviderEntityId],
[FiscalId], [BusinessName], [AddressName], [PostalCode],
[CityName], [CountryDescr], [StateId], [PhoneNbr],
[SystemId], [ActiveFlag], [ISO2Value], [ISO3Value],
[InfoBusinessTypeId])
SELECT DISTINCT [EntityId], [EntityType], [VendorId], [ProviderEntityId],
[FiscalId], [BusinessName], [AddressName], [PostalCode],
[CityName], [CountryDescr], [StateId], [PhoneNbr], [SystemId],
[ActiveFlag], [ISO2Value], [ISO3Value], [InfoBusinessTypeId]
FROM [#tmpEntityXml]
WHERE VendorId IS NOT NULL AND ProviderEntityId IS NOT NULL AND ISO2Value IS NOT NULL
-- Inserts tmpEntityIDs
INSERT INTO [#tmpEntityIDs]
([EntityId], [VendorId], [ProviderEntityId], [IDType], [IdentificationValue])
SELECT DISTINCT [EntityId], [VendorId], [ProviderEntityId], [IDType], [IdentificationValue]
FROM [#tmpEntityXml]
WHERE VendorId IS NOT NULL AND ProviderEntityId IS NOT NULL AND ISO2Value IS NOT NULL AND
IDType IS NOT NULL AND IdentificationValue IS NOT NULL
-- Drops table
DROP TABLE [#tmpEntityXml];
-- ******************************
-- 3.- TADIR_Entity
-- ******************************
-- 3.1.- Update TADIR_Entity (when necessary)
UPDATE [SingleDirectory].[TADIR_Entity]
SET [ActiveFlag] = [#tmpEntity].[ActiveFlag],
[AddressName] = (CASE WHEN [#tmpEntity].[AddressName] IS NOT NULL THEN [#tmpEntity].[AddressName] ELSE [SingleDirectory].[TADIR_Entity].[AddressName] END),
[BusinessName] = (CASE WHEN [#tmpEntity].[BusinessName] IS NOT NULL THEN [#tmpEntity].[BusinessName] ELSE [SingleDirectory].[TADIR_Entity].[BusinessName] END),
[CityName] = (CASE WHEN [#tmpEntity].[CityName] IS NOT NULL THEN [#tmpEntity].[CityName] ELSE [SingleDirectory].[TADIR_Entity].[CityName] END),
[CountryDescr] = (CASE WHEN [#tmpEntity].[CountryDescr] IS NOT NULL THEN [#tmpEntity].[CountryDescr] ELSE [SingleDirectory].[TADIR_Entity].[CountryDescr] END),
[EntityType] = [#tmpEntity].[EntityType],
[FiscalId] = (CASE WHEN [#tmpEntity].[FiscalId] IS NOT NULL THEN [#tmpEntity].[FiscalId] ELSE [SingleDirectory].[TADIR_Entity].[FiscalId] END),
[ISO2Value] = (CASE WHEN [#tmpEntity].[ISO2Value] IS NOT NULL THEN [#tmpEntity].[ISO2Value] ELSE [SingleDirectory].[TADIR_Entity].[ISO2Value] END),
[ISO3Value] = (CASE WHEN [#tmpEntity].[ISO3Value] IS NOT NULL THEN [#tmpEntity].[ISO3Value] ELSE [SingleDirectory].[TADIR_Entity].[ISO3Value] END),
[InfoBusinessTypeId] = (CASE WHEN [#tmpEntity].[InfoBusinessTypeId] IS NOT NULL THEN [#tmpEntity].[InfoBusinessTypeId] ELSE [SingleDirectory].[TADIR_Entity].[InfoBusinessTypeId] END),
[PhoneNbr] = (CASE WHEN [#tmpEntity].[PhoneNbr] IS NOT NULL THEN [#tmpEntity].[PhoneNbr] ELSE [SingleDirectory].[TADIR_Entity].[PhoneNbr] END),
[PostalCode] = (CASE WHEN [#tmpEntity].[PostalCode] IS NOT NULL THEN [#tmpEntity].[PostalCode] ELSE [SingleDirectory].[TADIR_Entity].[PostalCode] END),
[ProviderEntityId] = (CASE WHEN [#tmpEntity].[ProviderEntityId] IS NOT NULL THEN [#tmpEntity].[ProviderEntityId] ELSE [SingleDirectory].[TADIR_Entity].[ProviderEntityId] END),
[StateId] = (CASE WHEN [#tmpEntity].[StateId] NOT LIKE 0 THEN [#tmpEntity].[StateId] ELSE [SingleDirectory].[TADIR_Entity].[StateId] END),
[SystemId] = (CASE WHEN [SingleDirectory].[TADIR_Entity].[SystemId] IS NULL THEN [#tmpEntity].[SystemId] ELSE [SingleDirectory].[TADIR_Entity].[SystemId] END),
[VendorId] = [#tmpEntity].[VendorId],
[UpdateDate] = GETUTCDATE()
FROM [SingleDirectory].[TADIR_Entity]
INNER JOIN [#tmpEntity]
ON ([SingleDirectory].[TADIR_Entity].[EntityId] = [#tmpEntity].[EntityId])
WHERE ([SingleDirectory].[TADIR_Entity].[ActiveFlag] IS NULL AND [#tmpEntity].[ActiveFlag] IS NOT NULL) OR ([SingleDirectory].[TADIR_Entity].[ActiveFlag] IS NOT NULL AND [#tmpEntity].[ActiveFlag] IS NULL) OR [SingleDirectory].[TADIR_Entity].[ActiveFlag]
NOT LIKE [#tmpEntity].[ActiveFlag]
OR ( [#tmpEntity].[AddressName] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[AddressName] IS NULL OR [SingleDirectory].[TADIR_Entity].[AddressName] NOT LIKE [#tmpEntity].[AddressName]))
OR ( [#tmpEntity].[BusinessName] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[BusinessName] IS NULL OR [SingleDirectory].[TADIR_Entity].[BusinessName] NOT LIKE [#tmpEntity].[BusinessName]))
OR ( [#tmpEntity].[CityName] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[CityName] IS NULL OR [SingleDirectory].[TADIR_Entity].[CityName] NOT LIKE [#tmpEntity].[CityName]))
OR ( [#tmpEntity].[CountryDescr] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[CountryDescr] IS NULL OR [SingleDirectory].[TADIR_Entity].[CountryDescr] NOT LIKE [#tmpEntity].[CountryDescr]))
OR ( [SingleDirectory].[TADIR_Entity].[EntityType] IS NULL AND [#tmpEntity].[EntityType] IS NOT NULL) OR ([SingleDirectory].[TADIR_Entity].[EntityType] IS NOT NULL AND [#tmpEntity].[EntityType] IS NULL) OR [SingleDirectory].[TADIR_Entity].[EntityType] NOT LIKE [#tmpEntity].[EntityType]
OR ( [#tmpEntity].[FiscalId] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[FiscalId] IS NULL OR [SingleDirectory].[TADIR_Entity].[FiscalId] NOT LIKE [#tmpEntity].[FiscalId]))
OR ( [#tmpEntity].[ISO2Value] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[ISO2Value] IS NULL OR [SingleDirectory].[TADIR_Entity].[ISO2Value] NOT LIKE [#tmpEntity].[ISO2Value]))
OR ( [#tmpEntity].[ISO3Value] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[ISO3Value] IS NULL OR [SingleDirectory].[TADIR_Entity].[ISO3Value] NOT LIKE [#tmpEntity].[ISO3Value]))
OR ( [#tmpEntity].[InfoBusinessTypeId] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[InfoBusinessTypeId] IS NULL OR [SingleDirectory].[TADIR_Entity].[InfoBusinessTypeId] NOT LIKE [#tmpEntity].[InfoBusinessTypeId]))
OR ( [#tmpEntity].[PhoneNbr] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[PhoneNbr] IS NULL OR [SingleDirectory].[TADIR_Entity].[PhoneNbr] NOT LIKE [#tmpEntity].[PhoneNbr]))
OR ( [#tmpEntity].[PostalCode] IS NOT NULL AND ([SingleDirectory].[TADIR_Entity].[PostalCode] IS NULL OR [SingleDirectory].[TADIR_Entity].[PostalCode] NOT LIKE [#tmpEntity].[PostalCode]))
OR ( [SingleDirectory].[TADIR_Entity].[ProviderEntityId] IS NULL AND [#tmpEntity].[ProviderEntityId] IS NOT NULL) OR ([SingleDirectory].[TADIR_Entity].[ProviderEntityId] IS NOT NULL AND [#tmpEntity].[ProviderEntityId] IS NULL) OR [SingleDirectory].[TADIR_Entity].[ProviderEntityId] NOT LIKE [#tmpEntity].[ProviderEntityId]
OR ( [#tmpEntity].[StateId] NOT LIKE 0 AND ([SingleDirectory].[TADIR_Entity].[StateId] IS NULL OR [SingleDirectory].[TADIR_Entity].[StateId] NOT LIKE [#tmpEntity].[StateId]))
OR ([SingleDirectory].[TADIR_Entity].[SystemId] IS NULL)
OR ( [SingleDirectory].[TADIR_Entity].[VendorId] IS NULL AND [#tmpEntity].[VendorId] IS NOT NULL) OR ( [SingleDirectory].[TADIR_Entity].[VendorId] IS NOT NULL AND [#tmpEntity].[VendorId] IS NULL) OR [SingleDirectory].[TADIR_Entity].[VendorId] NOT LIKE [#tmpEntity].[VendorId]
-- 3.2.- INSERTS into TADIR_Entity not identified emtotoes
SET #currentDateTime = GETUTCDATE()
-- INSERT INTO TADIR_Entity
INSERT INTO [SingleDirectory].[TADIR_Entity] ([EntityType],
[VendorId],
[ProviderEntityId],
[FiscalId],
[BusinessName],
[AddressName],
[PostalCode],
[CityName],
[CountryDescr],
[StateId],
[PhoneNbr],
[SystemId],
[ActiveFlag],
[ISO2Value],
[ISO3Value],
[InfoBusinessTypeId],
[CreationDate],
[UpdateDate])
OUTPUT INSERTED.EntityId, INSERTED.VendorId, INSERTED.ProviderEntityId INTO [#tmpEntityInserted]
SELECT [#tmpEntity].[EntityType],
[#tmpEntity].[VendorId],
[#tmpEntity].[ProviderEntityId],
[#tmpEntity].[FiscalId],
[#tmpEntity].[BusinessName],
[#tmpEntity].[AddressName],
[#tmpEntity].[PostalCode],
[#tmpEntity].[CityName],
[#tmpEntity].[CountryDescr],
[#tmpEntity].[StateId],
[#tmpEntity].[PhoneNbr],
[#tmpEntity].[SystemId],
[#tmpEntity].[ActiveFlag],
[#tmpEntity].[ISO2Value],
[#tmpEntity].[ISO3Value],
[#tmpEntity].[InfoBusinessTypeId],
#currentDateTime,
#currentDateTime
FROM [#tmpEntity]
WHERE [#tmpEntity].[EntityId] IS NULL
-- UPDATE [#tmpEntityXml].[EntityId]
UPDATE [#tmpEntity]
SET [EntityId] = [#tmpEntityInserted].[EntityId]
FROM [#tmpEntity]
INNER JOIN [#tmpEntityInserted]
ON ([#tmpEntity].[ProviderEntityId] = [#tmpEntityInserted].[ProviderEntityId]
AND [#tmpEntity].[VendorId] = [#tmpEntityInserted].[VendorId])
-- 3.3.- Update EntityId ON [#tmpEntityIDs]
UPDATE [#tmpEntityIDs]
SET [EntityId] = [#tmpEntity].[EntityId]
FROM [#tmpEntityIDs]
INNER JOIN [#tmpEntity]
ON ([#tmpEntityIDs].[VendorId] = [#tmpEntity].[VendorId]
AND [#tmpEntityIDs].[ProviderEntityId] = [#tmpEntity].[ProviderEntityId]
AND [#tmpEntityIDs].[EntityId] IS NULL)
-- ******************************
-- 4.- TADIR_EntityIDs
-- ******************************
-- 4.1.- DELETE old values
DELETE [SingleDirectory].[TADIR_EntityIDs]
FROM [SingleDirectory].[TADIR_EntityIDs]
INNER JOIN [#tmpEntity]
ON ([SingleDirectory].[TADIR_EntityIDs].[EntityId] = [#tmpEntity].[EntityId])
LEFT JOIN [#tmpEntityIDs]
ON ([SingleDirectory].[TADIR_EntityIDs].[EntityId] = [#tmpEntityIDs].[EntityId]
AND [SingleDirectory].[TADIR_EntityIDs].[IDType] = [#tmpEntityIDs].[IDType])
WHERE [#tmpEntityIDs].[EntityId] IS NULL
-- 4.2.- UPDATE values
UPDATE [SingleDirectory].[TADIR_EntityIDs]
SET [IdentificationValue] = [#tmpEntityIDs].[IdentificationValue]
FROM [SingleDirectory].[TADIR_EntityIDs]
INNER JOIN [#tmpEntityIDs]
ON ([#tmpEntityIDs].[EntityId] = [SingleDirectory].[TADIR_EntityIDs].[EntityId] AND
[#tmpEntityIDs].[IDType] = [SingleDirectory].[TADIR_EntityIDs].[IDType])
WHERE [#tmpEntityIDs].[IdentificationValue] NOT LIKE [SingleDirectory].[TADIR_EntityIDs].[IdentificationValue]
-- 4.3.- INSERT values
INSERT INTO [SingleDirectory].[TADIR_EntityIDs] ([EntityId],
[IDType],
[IdentificationValue])
SELECT [#tmpEntityIDs].[EntityId],
[#tmpEntityIDs].[IDType],
[#tmpEntityIDs].[IdentificationValue]
FROM [#tmpEntityIDs]
LEFT JOIN [SingleDirectory].[TADIR_EntityIDs]
ON ([#tmpEntityIDs].[EntityId] = [SingleDirectory].[TADIR_EntityIDs].[EntityId]
AND [#tmpEntityIDs].[IDType] = [SingleDirectory].[TADIR_EntityIDs].[IDType])
WHERE [SingleDirectory].[TADIR_EntityIDs].[EntityId] IS NULL
-- ******************************
-- 5.- Loads the return results.
-- ******************************
SELECT DISTINCT [SingleDirectory].[TADIR_Entity].*, [SingleDirectory].[TADIR_EntityIDs].[IDType], [SingleDirectory].[TADIR_EntityIDs].[IdentificationValue]
FROM [SingleDirectory].[TADIR_Entity]
INNER JOIN [#tmpEntity]
ON ([SingleDirectory].[TADIR_Entity].[EntityId] = [#tmpEntity].[EntityId] )
LEFT JOIN [SingleDirectory].[TADIR_EntityIDs]
ON ([SingleDirectory].[TADIR_Entity].[EntityId] = [SingleDirectory].[TADIR_EntityIDs].[EntityId])
WHERE [#tmpEntity].[EntityId] IS NOT NULL
-- ******************************
-- 6.- Free memory
-- ******************************
DROP INDEX INDEXEntityId ON [#tmpEntity]
DROP INDEX INDEXProviderEntityId ON [#tmpEntity]
DROP INDEX INDEXFiscalId ON [#tmpEntity]
DROP TABLE [#tmpEntity]
DROP INDEX INDEXProviderEntityId ON [#tmpEntityInserted]
DROP TABLE [#tmpEntityInserted]
DROP INDEX INDEXProviderEntityId ON [#tmpEntityIDs]
DROP INDEX INDEXEntityId ON [#tmpEntityIDs]
DROP TABLE [#tmpEntityIDs]
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK TRAN;
INSERT INTO [Log].[tasip_errorlogdb]
(errorcode,
errorstatusvalue,
procedurevalue,
descriptionmessagetext,
wrongtracecode,
date)
VALUES (Error_number(),
Error_state(),
Error_procedure(),
Error_message(),
Error_line(),
Getutcdate());
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH
IF ##TRANCOUNT > 0
COMMIT TRAN;

building Snapshot table from audit trail in ms sql

I'm faced with the same problem related here Building a snapshot table from audit records. The code bellow solve partially my problem
Select * into #temp from (
SELECT Audit.PrimaryKeyValue as ID,Audit.FieldName,OldValue FROM audit left JOIN (
SELECT Audit.FieldName,Audit.PrimaryKeyValue, MAX(UpdateDate) AS dateadded FROM audit GROUP BY FieldName,PrimaryKeyValue
) maxtimestamp ON audit.FieldName = maxtimestamp.FieldName AND audit.updateDate = maxtimestamp.dateadded
where PrimaryKeyField='Id' and cast(UpdateDate as date)<=#Data) src
pivot(
max(src.OldValue)
for FieldName in (Centrala,ID_Grup,Pi, Ci, Pmt, Pneta, Rpp, Pd, UD, Suport1, Suport2, Suport3, Stare,
Motiv, Observatii, Comentarii, Un, Data_ADD, Modified_Date, Scada, Fuel_base)
) piv;
How to obtain a snapshot of a table based on records from audit trail table at a given moment.
By copying actual table in a temp one and by updating values from it based on content of audit is a solution?
My English is poor!
Thanks!!!
The structure of the primary table is:
[ID] [int] IDENTITY(1,1) NOT NULL,
[Centrala] [int] NOT NULL,
[ID_grup] [nvarchar](50) NULL,
[Pi] [float] NULL,
[Ci] [float] NULL,
[Pmt] [float] NULL,
[Pneta] [float] NULL,
[Rpp] [float] NULL,
[Pd] [float] NULL,
[UD] [nvarchar](50) NULL,
[Suport1] [nvarchar](255) NULL,
[Suport2] [nvarchar](255) NULL,
[Suport3] [nvarchar](255) NULL,
[Stare] [int] NULL,
[Motiv] [nvarchar](max) NULL,
[Observatii] [nvarchar](max) NULL,
[Comentarii] [nvarchar](max) NULL,
[Un] [varchar](10) NULL,
[Data_ADD] [date] NULL,
[Modified_Date] [date] NULL,
[Scada] [nvarchar](100) NULL,
[Fuel_base] [nvarchar](255) NULL,
and the structure of the Audit table is:
[AuditID] [int] IDENTITY(1,1) NOT NULL,
[Type] [char](1) NULL,
[TableName] [varchar](128) NULL,
[PrimaryKeyField] [varchar](1000) NULL,
[PrimaryKeyValue] [varchar](1000) NULL,
[FieldName] [varchar](128) NULL,
[OldValue] [varchar](1000) NULL,
[NewValue] [varchar](1000) NULL,
[UpdateDate] [datetime] NULL,
[UserName] [varchar](128) NULL
Users can modify values in primary table inclusive deleting entire rows and Audit table catch all modifications.I have to do a report with content of primary table at certain date back in time. I think the columns name in Audit table are expressive, Type has three values 'U','I','D' for update,insert and delete actions. Another problem is that if the Audit table contain modification for rows in primary table and the date for snapshot is lower than updateDate in Audit then I have to choose OldValue else NewValue. It is correct?
Thank you #Nick.McDermaid for your reply!!
I found an extremely ugly solution, but I think it works fine by now
Declare #data date
select #data='2016.02.2'
select * into #Grup1 from Grupuri
--Apply to actual values most oldest values from Audit
select * into #temp from (
SELECT
Audit.PrimaryKeyValue as ID,Audit.FieldName,OldValue
FROM audit inner JOIN (
SELECT Audit.FieldName,Audit.PrimaryKeyValue, min(UpdateDate) AS dateadded FROM audit GROUP BY FieldName,PrimaryKeyValue
) maxtimestamp ON audit.FieldName = maxtimestamp.FieldName AND audit.updateDate = maxtimestamp.dateadded
where PrimaryKeyField='Id' and TableName='Grupuri' ) src
pivot(
max(src.OldValue)
for FieldName in (Centrala,ID_Grup,Pi, Ci, Pmt, Pneta, Rpp, Pd, UD, Suport1, Suport2, Suport3, Stare,
Motiv, Observatii, Comentarii, Un, Data_ADD, Modified_Date, Scada, Fuel_base)
) piv;
UPDATE #Grup1 SET Pi= (case When b.Pi is not null then b.Pi else #Grup1.Pi end),
Ci=case When b.Ci is not null then b.Ci else #Grup1.Ci end,
Pmt=case When b.Pmt is not null then b.Pmt else #Grup1.Pmt end,
Pneta=case When b.Pneta is not null then b.Pneta else #Grup1.Pneta end,
Rpp=case When b.Rpp is not null then b.Rpp else #Grup1.Rpp end,
Pd=case When b.Pd is not null then b.Pd else #Grup1.Pd end,
UD=case When b.Ud is not null then b.Ud else NULL end,
Suport1=case When b.Suport1 is not null then b.Suport1 else #Grup1.Suport1 end,
Suport2=case When b.Suport2 is not null then b.Suport2 else #Grup1.Suport2 end,
Suport3=case When b.Suport3 is not null then b.Suport3 else #Grup1.Suport3 end,
Stare=case When b.Stare is not null then b.Stare else #Grup1.Stare end,
Motiv=case When b.Motiv is not null then b.Motiv else #Grup1.Motiv end,
Observatii=case When b.Observatii is not null then b.Observatii else #Grup1.Observatii end,
Comentarii=case When b.Comentarii is not null then b.Comentarii else #Grup1.Comentarii end,
Un=case When b.Un is not null then b.Un else #Grup1.Un end,
Scada= case When b.Scada is not null then b.Scada else #Grup1.Scada end,
Fuel_base=case When b.Fuel_base is not null then b.Fuel_base else #Grup1.Fuel_base end
FROM #temp b WHERE #Grup1.id = b.id
--Apply new values updated up to #data
select * into #temp1 from (
SELECT
Audit.PrimaryKeyValue as ID,Audit.FieldName,NewValue
FROM audit left JOIN (
SELECT Audit.FieldName,Audit.PrimaryKeyValue, MAX(UpdateDate) AS dateadded FROM audit GROUP BY FieldName,PrimaryKeyValue
) maxtimestamp ON audit.FieldName = maxtimestamp.FieldName AND audit.updateDate = maxtimestamp.dateadded
where PrimaryKeyField='Id' and TableName='Grupuri'
and cast(UpdateDate as date) <=#Data) src
pivot(
max(src.NewValue)
for FieldName in (Centrala,ID_Grup,Pi, Ci, Pmt, Pneta, Rpp, Pd, UD, Suport1, Suport2, Suport3, Stare,
Motiv, Observatii, Comentarii, Un, Data_ADD, Modified_Date, Scada, Fuel_base)) piv;
UPDATE #Grup1 SET Pi= (case When b.Pi is not null then b.Pi else #Grup1.Pi end),
Ci=case When b.Ci is not null then b.Ci else #Grup1.Ci end,
Pmt=case When b.Pmt is not null then b.Pmt else #Grup1.Pmt end,
Pneta=case When b.Pneta is not null then b.Pneta else #Grup1.Pneta end,
Rpp=case When b.Rpp is not null then b.Rpp else #Grup1.Rpp end,
Pd=case When b.Pd is not null then b.Pd else #Grup1.Pd end,
UD=case When b.Ud is not null then b.Ud else '-' end,
Suport1=case When b.Suport1 is not null then b.Suport1 else #Grup1.Suport1 end,
Suport2=case When b.Suport2 is not null then b.Suport2 else #Grup1.Suport2 end,
Suport3=case When b.Suport3 is not null then b.Suport3 else #Grup1.Suport3 end,
Stare=case When b.Stare is not null then b.Stare else #Grup1.Stare end,
Motiv=case When b.Motiv is not null then b.Motiv else #Grup1.Motiv end,
Observatii=case When b.Observatii is not null then b.Observatii else #Grup1.Observatii end,
Comentarii=case When b.Comentarii is not null then b.Comentarii else #Grup1.Comentarii end,
Un=case When b.Un is not null then b.Un else #Grup1.Un end,
Scada= case When b.Scada is not null then b.Scada else #Grup1.Scada end,
Fuel_base=case When b.Fuel_base is not null then b.Fuel_base else #Grup1.Fuel_base end
FROM #temp1 b
WHERE #Grup1.id = b.id
Delete from #Grup1 where Data_ADD>#data
Select * from #Grup1
union
Select Old_ID,Centrala,ID_Grup,Pi, Ci, Pmt, Pneta, Rpp, Pd, UD, Suport1,Suport2, Suport3, Stare, Motiv,
Observatii, Comentarii, Un, Data_ADD, Modified_Date, Scada, Fuel_base From DeletedGrupuri where Deleted<=#Data and Old_ID is not null order by ID
drop table #temp
drop table #temp1
drop table #Grup1
If someone has a better solution or can improve this code please help me. Also I'm open to modify the design of table Audit to simplify this process.
Thank You!

How to use multiple conditions in the where clause?

I'm a rookie to SQL Server. I'm using SQL Server 2008 R2. I have created two tables called adding_hanger and allot as follows
CREATE TABLE [dbo].[adding_hanger]
(
[End_Id] [bigint] IDENTITY(1,1) NOT NULL,
[Hanger_Location] [char](10) NOT NULL,
[Hanger_Capacity] [int] NOT NULL,
[Hanger_Id] AS ((CONVERT([varchar](100),substring([Hanger_Location],(1),(3)),0)+'101')+CONVERT([varchar](100),[End_Id],0)) PERSISTED NOT NULL,
[Manager_Name] [varchar](15) NOT NULL,
[Manager_Id] AS ((CONVERT([varchar](4),substring([Social_Security_No],(8),(4)),0)+'31')+CONVERT([varchar](100),[End_Id],0)) PERSISTED NOT NULL,
[Manager_Password] AS ((CONVERT([varchar](3),substring([Manager_Name],(1),(3)),0)+'#')+CONVERT([varchar](3),substring([Hanger_Location],(1),(3)),0)),
[Social_Security_No] [varchar](15) NOT NULL,
[Date_of_Birth] [datetime] NOT NULL,
[Gender] [varchar](8) NOT NULL,
[Mobile_No] [varchar](50) NOT NULL,
[Email_Address] [varchar](30) NOT NULL,
[House_No] [varchar](10) NOT NULL,
[Address_Line_1] [varchar](30) NOT NULL,
[Address_id] AS ((CONVERT([varchar](100),substring([City],(1),(3)),0)+'31')+CONVERT([varchar](100),[End_Id],0)) PERSISTED NOT NULL,
[City] [char](15) NOT NULL,
[State] [char](15) NOT NULL,
[Country] [char](15) NOT NULL,
[Pin_No] [int] NOT NULL
)
CREATE TABLE [dbo].[allot]
(
[Fromdate] [datetime] NULL,
[todate] [datetime] NULL,
[hangarlocation] [char](10) NULL,
[hangarno] [varchar](100) NULL,
[planeid] [varchar](100) NULL
)
How do I fetch the details of the available hangers that are not allotted within a given range of from and to dates given as input and also not exceeding the capacity of the hanger if allocated already?
First, your spelling of 'hangar' is inconsistent and should be addressed.
I'm assuming that the hangar capacity represents how many allots you can store in that hangar? If so, the hangar capacity might vary over a given timeframe as allots are added/removed (according to FromDate and ToDate), so your question isn't clear. If you want a hangar that definitely has a space free over a given period, I would use:
declare #from_date datetime, #end_date datetime, #i int
-- Set your start and end dates (replace the dates below with the correct ones)
set #from_date = '2016-07-01'
set #to_date = '2016-07-31'
set #i = 1 -- counter
-- Create a table of dates
select #from_date as date into #dates
while dateadd(day,#i,#from_date) <= #to_date
begin
insert into #dates values (dateadd(day,#i,#from_date))
end
-- Create table of date, hangar_id, hangar_capacity
select date, hangar_id, hangar_capacity
into #dates_by_hangar
from adding_hangar
inner join #dates on 1 = 1
-- Table showing hangars with at least one free space on every date in the range
select hangar_id from (
-- 2. Table showing hangar space free on each date
select a.*, a.hanger_capacity - isnull(b.allots_in_hangar,0) as hangar_space_free
from #dates_by_hangar a
left outer join (
-- 1. Table showing number of allots in each hangar on a given date
select date, hangar_no, sum(case when b.hangar_no is not null then 1 else 0 end) as allots_in_hangar
from #dates a
left outer join allot b
on a.date between b.fromdate and b.todate
group by date, hangar_no) b
on a.hangar_id = b.hangar_no
and a.date = b.date
)
group by hangar_no
having max(hangar_space_free) >= 1
SELECT ah.* from [adding_hanger] AS ah
INNER JOIN [allot] ON allot.hangarlocation = ah.Hanger_Location
WHERE (allot.Fromdate < <input_from_date> OR allot.todate > <input_to_date>)
OR (allot.Fromdate >= <input_from_date> AND allot.todate <= <input_to_date> AND ah.Hanger_Capacity <= <input_capacity>)

Resources