Appointment Slots not working - sql-server

I have three tables.
Table 1.(Booking)
CREATE TABLE [dbo].[Booking](
[Booking_Serno] [int] IDENTITY(1,1) NOT NULL,
[Dt] [datetime] NULL,
[start] [nvarchar](50) NULL,
[todate] [nvarchar](50) NULL,
[Service_Id] [int] NULL
) ON [PRIMARY]
INSERT [dbo].[Booking] ([Booking_Serno], [Dt], [start], [todate], [Service_Id]) VALUES (1, CAST(0x0000A6DA00000000 AS DateTime), N'9:30 AM', N'10:00 AM', 1)
GO
Table 2.(Service)
CREATE TABLE [dbo].[Service](
[Service_Serno] [int] IDENTITY(1,1) NOT NULL,
[Service_Duration] [int] NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Service] ON
INSERT [dbo].[Service] ([Service_Serno], [Service_Duration]) VALUES (1, 30)
Table 3 (Rules)
CREATE TABLE [dbo].[Rules](
[Rule_Serno] [int] IDENTITY(1,1) NOT NULL,
[Start_Dt] [varchar](50) NULL,
[End_Dt] [varchar](50) NULL,
[from_dt] [varchar](50) NULL,
[to_dt] [varchar](50) NULL,
[Service_Id] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Rules] ON
INSERT [dbo].[Rules] ([Rule_Serno], [Start_Dt], [End_Dt], [from_dt], [to_dt], [Service_Id]) VALUES (1, N'2016-07-02', N'2016-07-13', N'07:00', N'17:00', 1)
I am running a stored procedure. It gets me the desired result but then I am trying to book a time by changing the interval, the slots shows empty even if there is a slot booked. Ex. If i am setting a slot for 60 minutes and book a slot from 7:00-8:00 it shows booked(xxx) but when i change the interval to 30 the 7:00-8:00 becomes available. It should actually display 7:00-7:30 and 7:00-8:00 unavailable.
the Stored Procedure is
Dt:-12/12/2016 ; ServiceId:-1
CREATE PROCEDURE [dbo].[RealGetFollowUp] #Dt varchar(50), #ServiceId int
AS
--declare #starttime datetime = '2015-10-28 12:00', #endtime datetime = '2015-10-28 14:00'
DECLARE #starttime varchar(50),
#endtime varchar(50),
#interval int
SELECT
#starttime = Rules.from_dt,
#endtime = Rules.to_dt,
#interval = Service.Service_Duration
FROM Service
INNER JOIN Rules
ON Service.Service_Serno = Rules.Service_Id
WHERE Service.Service_Serno = #ServiceId
--SELECT * INTO #tmp FROM d;
DECLARE #slots int
SELECT
#slots = DATEDIFF(MINUTE, #starttime, #endtime) / #interval
SELECT TOP (#slots)
N = IDENTITY(int, 1, 1) INTO #Numbers
FROM master.dbo.syscolumns a
CROSS JOIN master.dbo.syscolumns b;
SELECT
DATEADD(MINUTE, ((n - 1) * #interval), #starttime) AS start,
DATEADD(MINUTE, (n * #interval), #starttime) AS todate INTO #slots
FROM #numbers
SELECT
#Dt AS 'Date',
LEFT(CONVERT(varchar, s.start, 108), 10) AS Start,
LEFT(CONVERT(varchar, s.todate, 108), 10) AS 'End',
CASE
WHEN b.start IS NULL THEN '-'
ELSE 'xx'
END AS Status
FROM [#slots] AS s
LEFT JOIN Booking AS b
ON s.start = b.start
AND s.todate = b.todate
AND b.Dt = #Dt
DROP TABLE #numbers, #slots
GO
I need to check if there is a slot booked in the Booking table and even if i change the interval in the service table, the slot booked in the booking table should be shown as booked.

Change the output SELECT in the sproc to...
SELECT
#Dt AS 'Date',
LEFT(CONVERT(varchar, s.start, 108), 10) AS Start,
LEFT(CONVERT(varchar, s.todate, 108), 10) AS 'End',
CASE
WHEN b.start IS NULL THEN '-'
ELSE 'xx'
END AS Status
FROM [#slots] AS s
LEFT JOIN Booking AS b
ON (
--Range is bigger than the meeting
(s.start <= b.start
AND s.todate >= b.todate)
OR
--Range is smaller than the meeting
(s.start Between b.start and b.toDate
AND s.todate Between b.start and b.toDate)
)
AND b.Dt = #Dt

Related

How to calculate running total from due amount in SQL Server

I have customer Table ID and Customer Name
CREATE TABLE [dbo].[Customer]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[CustomerName] [nvarchar](500) NULL
) ON [PRIMARY]
I have Payment Schedule Table each customer may have different schedule
CREATE TABLE [dbo].[SchedulePayment]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Date] [date] NULL,
[Amount] [decimal](18, 0) NULL,
[CustomerID] [int] NULL
) ON [PRIMARY]
I have ReceivedPayment table:
CREATE TABLE [dbo].[ReceivedPayment]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NULL,
[ReceivedAmount] [decimal](18, 0) NULL,
[ReceivedDate] [date] NULL
) ON [PRIMARY]
I want to deduct received amount from the schedule amount and show the remaining amount till today month and year future amount would be 0 because it is not due now but if customer pay extra then it will show in the future months
I want below output
SELECT rp.CustomerID,[date] ScheduleDate, ReceivedAmount,
(SumAmount -
SUM(ReceivedAmount)
OVER (PARTITION BY rp.CustomerID ORDER BY Receiveddate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
) AS PendingAmount
,Amount AS ScheduleAmount
FROM
(SELECT [date], Amount, CustomerID,
(SUM(amount)
OVER (PARTITION BY CustomerID ORDER BY [date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
) AS SumAmount
FROM SchedulePayment) sp
JOIN ReceivedPayment rp ON rp.CustomerID = sp.CustomerID
AND ReceivedDate >= [date]
AND
(
(DATEPART(MM,ReceivedDate)=DATEPART(MM,[date]))
AND (DATEPART(YYYY,ReceivedDate)=DATEPART(YYYY,[date]))
)
ORDER BY rp.CustomerID,ReceivedDate,[date]
i looked at it too, and there is more going on here than can be explained at first glance. in normal payment posting, a balance carry forward rule to be held pending apply, and another rule would exist as the first of the month occurs, for payments in excess of payment due let alone no arrears. the solution has some rules than in all intense purposes is not necessarily database driven yet process and application driven from an accounting a/r perspective. here is some sample testing I did just to see how close I could come yet then realized expected output requires rules and dates and what I call float.
use test1
/*
CREATE TABLE [dbo].[Customer]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[CustomerName] [nvarchar](500) NULL
) ON [PRIMARY]
-- drop table customer
insert into customer select ('Customer1')
insert into customer select ('Customer2')
select * from customer
CREATE TABLE [dbo].[SchedulePayment]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Date] [date] NULL,
[Amount] money NULL,
[CustomerID] [int] NULL
) ON [PRIMARY]
insert into SchedulePayment values ('2022-01-01', 1000, 1)
insert into SchedulePayment values ('2022-02-01', 1000, 1)
insert into SchedulePayment values ('2022-03-01', 1000, 1)
insert into SchedulePayment values ('2022-04-01', 1000, 1)
insert into SchedulePayment values ('2022-01-01', 1000, 2)
insert into SchedulePayment values ('2022-02-01', 1000, 2)
insert into SchedulePayment values ('2022-03-01', 1000, 2)
insert into SchedulePayment values ('2022-04-01', 1000, 2)
-- drop table schedulepayment
select * from schedulepayment
CREATE TABLE [dbo].[ReceivedPayment]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [int] NULL,
[ReceivedAmount] money NULL,
[ReceivedDate] [date] NULL
) ON [PRIMARY]
insert into ReceivedPayment values (1, 500, '2022-01-06')
insert into ReceivedPayment values (1, 1500, '2022-02-15')
insert into ReceivedPayment values (1, 500, '2022-03-10')
insert into ReceivedPayment values (2, 100, '2022-01-01')
insert into ReceivedPayment values (2, 500, '2022-02-06')
insert into ReceivedPayment values (2, 400, '2022-02-08')
insert into ReceivedPayment values (2, 600, '2022-03-04')
-- drop table receivedpayment
select * from receivedpayment
*/
create table #t
(CustomerID int,
ScheduleDate date,
ReceivedAmount money,
PendingAmount money,
ScheduledAmount money
)
insert into #t (customerid, scheduledate, scheduledamount)
select
distinct customer.ID,
schedulepayment.date,
schedulepayment.Amount
from customer
left join schedulepayment on SchedulePayment.CustomerID = customer.ID
select * from #t
drop table #t
-- below is a pay flow by yet not a balance over paid and carry over to be spread
select
SchedulePayment.CustomerID,
SchedulePayment.Date,
ReceivedAmount = sum(ReceivedPayment.ReceivedAmount)
from ReceivedPayment
join SchedulePayment on ReceivedPayment.CustomerID = SchedulePayment.CustomerID
where datepart(month, SchedulePayment.Date) = datepart(month, ReceivedPayment.ReceivedDate) and datepart(year, schedulepayment.Date) = datepart(year, ReceivedPayment.ReceivedDate)
GROUP BY SchedulePayment.CustomerID, SchedulePayment.Date

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;

How to insert data in table using Insert Query from values provided in parameters

I have this table structure and I want to write Insert Query that'll insert data into the table from the values provided in parameters
CREATE TABLE [dbo].[EMPLOYEE](
[ID] [int] NULL,
[EMPLOYEE_NAME] [varchar](50) NULL,
[DEPARTMENT_ID] [int] NULL,
) ON [PRIMARY]
DECLARE #ID VARCHAR(20) = '1, 2';
DECLARE #Name VARCHAR(50) = 'Asim Asghar, Ahmad'
DECLARE #DeptID VARCHAR(20) = '5, 12';
INSERT INTO EMPLOYEE VALUES (#ID, #Name, #DeptID)
Based on the data provided above it should add 4 rows with following data
1 Asim Asghar 5
2 Ahmad 5
1 Asim Asghar 12
2 Ahmad 12
Hope someone can help
You can not pass multiple values together through a variable at a time. The script should be as below considering one person at a time-
CREATE TABLE [dbo].[EMPLOYEE](
[ID] [int] NULL,
[EMPLOYEE_NAME] [varchar](50) NULL,
[DEPARTMENT_ID] [int] NULL,
) ON [PRIMARY]
DECLARE #ID INT = 1;
DECLARE #Name VARCHAR(50) = 'Asim Asghar';
DECLARE #DeptID INT = 5;
INSERT INTO EMPLOYEE(ID,EMPLOYEE_NAME,DEPARTMENT_ID) VALUES (#ID, #Name, #DeptID)
Then you can change the values for next person and execute the INSERT script again. And from the second execution, you have to skip the Table creation script other wise it will through error.
The question's query is trying to insert a single row, using strings values for the ID and DeptID fields. This will fail with a runtime error.
One can use the table value constructor syntax to insert multiple rows in a single INSERT statement :
INSERT INTO EMPLOYEE
VALUES
(1, 'Asim Asghar', 5),
(2, 'Ahmad', 5),
(1, 'Asim Asghar', 12),
(2, 'Ahmad', 12)
The values can come from parameters or variables.
Using duplicate IDs and names in an Employee table hints at a problem. Looks like the intent is to store employees and their department assignments. Otherwise why insert 4 rows instead of 8 with all possible combinations?
Employee should be changed to this :
CREATE TABLE [dbo].[EMPLOYEE]
(
[ID] [int] primary key not null,
[EMPLOYEE_NAME] [varchar](50)
)
And another table, EmployeeAssignment should be added
CREATE TABLE [dbo].[EMPLOYEE_ASSIGNMENT]
(
Employee_ID int not null FOREIGN KEY REFERENCES EMPLOYEE(ID),
[DEPARTMENT_ID] [int] not NULL,
PRIMARY KEY (Employee_ID,Department_ID)
)
The data can be inserted with two INSERT statements :
INSERT INTO EMPLOYEE
VALUES
(1, 'Asim Asghar'),
(2, 'Ahmad'),
INSERT INTO EMPLOYEE_ASSIGNMENT
VALUES
(1, 5),
(2, 5),
(1, 12),
(2, 12)
Try this, You need this function for splitting by char using dynamic delimiter.
CREATE FUNCTION UDF_SPLIT_BY_CHAR(#STRING VARCHAR(8000), #DELIMITER CHAR(1))
RETURNS #TEMPTABLE TABLE (S_DATA VARCHAR(8000))
AS
BEGIN
DECLARE #IDX INT=1,#SLICE VARCHAR(8000)
IF LEN(#STRING)<1 OR #STRING IS NULL RETURN
WHILE #IDX<> 0
BEGIN
SET #IDX = CHARINDEX(#DELIMITER,#STRING)
IF #IDX!=0
SET #SLICE = LEFT(#STRING,#IDX - 1)
ELSE
SET #SLICE = #STRING
IF(LEN(#SLICE)>0)
INSERT INTO #TEMPTABLE(S_DATA) VALUES(#SLICE)
SET #STRING = RIGHT(#STRING,LEN(#STRING) - #IDX)
IF LEN(#STRING) = 0 BREAK
END
RETURN
END
Declare #EMPLOYEE TABLE
(
[ID] [int] NULL,
[EMPLOYEE_NAME] [varchar](50) NULL,
[DEPARTMENT_ID] [int] NULL
)
DECLARE #ID VARCHAR(20) = '1, 2'
,#Name VARCHAR(50) = 'Asim Asghar, Ahmad'
,#DeptID VARCHAR(20) = '5, 12';
insert into #EMPLOYEE
(
[ID],[EMPLOYEE_NAME],[DEPARTMENT_ID]
)
Select a.S_DATA,b.S_DATA,c.S_DATA
from dbo.UDF_SPLIT_BY_CHAR(#id,',') a
left join dbo.UDF_SPLIT_BY_CHAR(#Name,',') b on 1=1
left join dbo.UDF_SPLIT_BY_CHAR(#DeptID,',') c on 1=1

After Trigger for Update and Insert failing

I am writing a trigger for keeping audit record for one table for Insert and Update records.
CREATE TABLE [dbo].[AppLog](
[TableName] [varchar](32) NOT NULL,
[ColumnName] [varchar](32) NOT NULL,
[RecordId] [varchar](20) NOT NULL,
[OldValue] [varchar](2000) NULL,
[NewValue] [varchar](2000) NULL,
[UpdatedBy] [varchar](200) NULL,
[UpdatedOn] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Persons](
[Personid] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](255) NOT NULL,
[FirstName] [varchar](255) NULL,
[Age] [int] NULL
) ON [PRIMARY]
GO
CREATE TRIGGER AuditRecord ON dbo.Persons
AFTER UPDATE, INSERT
AS
INSERT INTO AppLog
(TableName ,ColumnName ,RecordId ,OldValue ,NewValue ,UpdatedBy ,UpdatedOn )
SELECT 'Persons', 'LastName', COALESCE(i.Personid,NULL),
d.LastName, i.LastName, CURRENT_USER, GETDATE()
FROM Persons pv
LEFT JOIN INSERTED i ON pv.Personid = i.Personid
LEFT JOIN DELETED d ON pv.Personid = d.Personid;
GO
INSERT INTO Persons (FirstName,LastName,age)
VALUES ('Satish','Parida',40);
INSERT INTO Persons (FirstName,LastName,age)
VALUES ('SKP','Tada',90);
The last insert is failing as it is trying to insert null to recordid column in applog table, could someone explain or fix the issue.
The statement that is failing is the one below:
INSERT INTO Persons (FirstName,LastName,age)
VALUES ('SKP','Tada',90);
This is because in your Trigger you are using Persons are your "base" table and the performing a LEFT JOIN to both inserted and deleted. As result when you try to perform the above INSERT, values from the previous INSERT are used as well in the trigger's dataset. The person 'Parida' doesn't appear in the table inserted for your second INSERT, and so COALESCE(i.Personid,NULL) returns NULL; as I mentioned in my comment, there' no point using COALESCE to return NULL, as if an expression's value evaluates to NULL it will return NULL. As RecordID (which is what COALESCE(i.Personid,NULL) is being inserted into) can't have the value NULL the INSERT fails and the whole transaction is rolled back.
I suspect that what you want for your trigger is the below:
CREATE TRIGGER AuditRecord ON dbo.Persons
AFTER UPDATE, INSERT
AS BEGIN
INSERT INTO AppLog (TableName,
ColumnName,
RecordId,
OldValue,
NewValue,
UpdatedBy,
UpdatedOn)
SELECT 'Persons',
'LastName',
i.Personid,
d.LastName,
i.LastName,
CURRENT_USER,
GETDATE()
FROM inserted AS i
LEFT JOIN deleted AS d ON i.Personid = d.Personid;
END;
inserted will always have at least 1 row for an UPDATE or an INSERT. inserted would not for a DELETE, but your trigger won't fire on that DML event so using inserted as the "base" table seems the correct choice.
Following code should work
CREATE TABLE [dbo].[AppLog](
[TableName] [varchar](32) NOT NULL,
[ColumnName] [varchar](32) NOT NULL,
[RecordId] [varchar](20) NOT NULL,
[OldValue] [varchar](2000) NULL,
[NewValue] [varchar](2000) NULL,
[UpdatedBy] [varchar](200) NULL,
[UpdatedOn] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Persons](
[Personid] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](255) NOT NULL,
[FirstName] [varchar](255) NULL,
[Age] [int] NULL
) ON [PRIMARY]
GO
CREATE TRIGGER AuditRecord ON dbo.Persons
AFTER UPDATE, INSERT
AS
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
BEGIN
INSERT INTO AppLog
(TableName ,ColumnName ,RecordId ,OldValue ,NewValue ,UpdatedBy ,UpdatedOn )
SELECT 'Persons', 'LastName', COALESCE(i.Personid,NULL),
d.LastName, i.LastName, CURRENT_USER, GETDATE()
FROM Persons pv
INNER JOIN INSERTED i ON pv.Personid = i.Personid
INNER JOIN DELETED d ON pv.Personid = d.Personid;
END
If exists (Select * from inserted) and not exists(Select * from deleted)
begin
INSERT INTO AppLog
(TableName ,ColumnName ,RecordId ,OldValue ,NewValue ,UpdatedBy ,UpdatedOn )
SELECT
'Persons', 'LastName',i.Personid,NULL,i.LastName,CURRENT_USER,GETDATE()
FROM
inserted AS i
END
GO
INSERT INTO Persons (FirstName,LastName,age)
VALUES ('Satish','Parida',40);
INSERT INTO Persons (FirstName,LastName,age)
VALUES ('SKP','Tada',90);
INSERT INTO Persons (FirstName,LastName,age)
VALUES ('abc','def',90);
INSERT INTO Persons (FirstName,LastName,age)
VALUES ('gg','hh',90);
UPDATE dbo.Persons SET LastName='Paridachanged' WHERE Personid=1
SELECT * FROM Persons
SELECT * FROM AppLog
USE KnockKnockDev;
GO
IF OBJECT_ID('dbo.AuditRecord', 'TR') IS NOT NULL
DROP TRIGGER dbo.AuditRecord;
GO
CREATE TRIGGER AuditRecord ON dbo.Persons
AFTER UPDATE, INSERT, DELETE
AS
DECLARE #Action as char(1)
DECLARE #Count as int
DECLARE #TableName as char(32)
DECLARE #ColumnName as char (32)
SET #TableName = 'Persons'
SET #ColumnName = 'LastName'
SET #Action = 'I' -- Set Action to 'I'nsert by default.
SELECT #Count = COUNT(*) FROM DELETED
IF #Count > 0
BEGIN
SELECT #Count = COUNT(*) FROM INSERTED
IF #Count > 0
SET #Action = 'U' -- Set Action to 'U'pdated.
ELSE
SET #Action = 'D' -- Set Action to 'D'eleted.
END
IF #Action = 'I'
BEGIN
INSERT INTO AppLog
(TableName ,ColumnName ,RecordId ,OldValue ,NewValue ,Action ,UpdatedBy ,UpdatedOn )
SELECT #TableName, #ColumnName, Personid,
NULL, LastName, #Action, CURRENT_USER, GETDATE()
FROM INSERTED;
END
ELSE IF #Action = 'D'
BEGIN
INSERT INTO AppLog
(TableName ,ColumnName ,RecordId ,OldValue ,NewValue ,Action ,UpdatedBy ,UpdatedOn )
SELECT #TableName, #ColumnName, Personid,
LastName, NULL, #Action, CURRENT_USER, GETDATE()
FROM DELETED;
END
ELSE
BEGIN
INSERT INTO AppLog
(TableName ,ColumnName ,RecordId ,OldValue ,NewValue ,Action ,UpdatedBy ,UpdatedOn )
SELECT #TableName, #ColumnName, i.Personid,
d.LastName, i.LastName, #Action, CURRENT_USER, GETDATE()
FROM Persons pv
INNER JOIN INSERTED i ON pv.Personid = i.Personid
INNER JOIN DELETED d ON pv.Personid = d.Personid;
END
GO

Converting a working script into Stored procedure

Posted this question yesterday and got a solution as well. The solution script works fine as-is but when I converted it into a stored procedure it gives wrong results. Not able to identify where exactly I am messing up with the code.
Table Schema:
CREATE TABLE [dbo].[VMaster](
[VID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[VName] [varchar](30) NOT NULL
)
GO
CREATE TABLE [dbo].[TblMaster](
[SID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[VID] [int] NOT NULL,
[CreatedDate] [datetime] default (getdate()) NOT NULL,
[CharToAdd] [varchar](10) NOT NULL,
[Start] [int] NOT NULL,
[End] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TblDetails](
[DetailsID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[SID] [int] NOT NULL,
[Sno] [int] NOT NULL,
[ConcatenatedText] [varchar](20) NOT NULL,
[isIssued] [bit] default (0) NOT NULL,
[isUsed] [bit] default (0) NOT NULL
)
GO
ALTER TABLE [dbo].[TblMaster] WITH CHECK ADD CONSTRAINT [fk_SI_id] FOREIGN KEY([VID])
REFERENCES [dbo].[VMaster] ([VID])
GO
ALTER TABLE [dbo].[TblMaster] CHECK CONSTRAINT [fk_SI_id]
GO
Working solution:
CREATE FUNCTION [dbo].[udf-Create-Range-Number] (#R1 money,#R2 money,#Incr money)
-- Syntax Select * from [dbo].[udf-Create-Range-Number](0,100,2)
Returns
#ReturnVal Table (RetVal money)
As
Begin
With NumbTable as (
Select NumbFrom = #R1
union all
Select nf.NumbFrom + #Incr
From NumbTable nf
Where nf.NumbFrom < #R2
)
Insert into #ReturnVal(RetVal)
Select NumbFrom from NumbTable Option (maxrecursion 32767)
Return
End
Declare #Table table (SID int,VID int,CreateDate DateTime,CharToAdd varchar(25),Start int, [End] Int)
Insert Into #Table values
(1,1,'2016-06-30 19:56:14.560','ABC',1,5),
(2,1,'2016-06-30 19:56:14.560','XYZ',10,20),
(3,2,'2016-06-30 19:56:14.560','P1',10,15)
Declare #Min int,#Max int
Select #Min=min(Start),#Max=max([End]) From #Table
Select B.SID
,Sno = A.RetVal
,ConcetratedText = concat(B.CharToAdd,A.RetVal)
From (Select RetVal=Cast(RetVal as int) from [dbo].[udf-Create-Range-Number](#Min,#Max,1)) A
Join #Table B on A.RetVal Between B.Start and B.[End]
Order By B.Sid,A.RetVal
Stored procedure (This generates more records than the working solution!!)
CREATE PROCEDURE [dbo].[Add_Details]
(
#VID INT,
#CreatedDate DATETIME,
#CharToAdd VARCHAR(10),
#Start INT,
#End INT
)
AS
SET NOCOUNT ON
BEGIN
DECLARE #SID INT
INSERT INTO [dbo].[TblMaster] (VID, CreatedDate, CharToAdd, Start, [End])
VALUES (#VID, #CreatedDate, #CharToAdd, #Start, #End)
SET #SID = SCOPE_IDENTITY()
DECLARE #Min INT, #Max INT
SELECT #Min = #Start, #Max = #End
INSERT INTO [dbo].[TblDetails] (SID, Sno, [ConcatenatedText])
SELECT #SID
,Sno = A.RetVal
,ConcatenatedText = CONCAT(B.CharToAdd,A.RetVal)
FROM (SELECT RetVal = CAST(RetVal AS INT) FROM [dbo].[udf-Create-Range-Number](#Min,#Max,1)) A
JOIN dbo.TblMaster B ON A.RetVal BETWEEN B.Start AND B.[End]
ORDER BY B.SID,A.RetVal
END
GO
Declare #tmp datetime
Set #tmp = getdate()
EXEC [dbo].[Add_Details]
#VID = 1,
#CreatedDate = #tmp,
#CharToAdd = 'ABC',
#Start = 1,
#End = 5
EXEC [dbo].[Add_Details]
#VID = 1,
#CreatedDate = #tmp,
#CharToAdd = 'XYZ',
#Start = 10,
#End = 20
EXEC [dbo].[Add_Details]
#VID = 2,
#CreatedDate = #tmp,
#CharToAdd = 'P1',
#Start = 10,
#End = 15
Output of working script:
Output of the stored procedure:
You need to filter by VID on the second insert. It's picking up rows from previous executions. Since it only picks up other rows where the ranges are overlapping it doesn't always do it. Run the procedure a few more times and you'll see the duplication amplified a lot more. The reason it didn't do this in the original code was because you were using a temp table that was recreated each time you ran it.
INSERT INTO [dbo].[TblDetails] (SID, Sno, [ConcatenatedText])
SELECT #SID
,Sno = A.RetVal
,ConcatenatedText = CONCAT(B.CharToAdd,A.RetVal)
FROM (
SELECT RetVal = CAST(RetVal AS INT)
FROM [dbo].[udf-Create-Range-Number](#Min,#Max,1)) A
JOIN dbo.TblMaster B ON A.RetVal BETWEEN B.Start AND B.[End]
WHERE B.VID = #VID -- <<<---------
)
On a side note I would highly recommend changing that function to type int rather than money.

Resources