Related
I would like to link rows in a self joined table with a trigger.
After an insert in a root table, I would like to create 3 "levels" in the child table.
And each of the level being a hierarchical data (or self joined) such as:
LVL1
LVL2
LVL3
Database is SQLSERVER.
I know there is a ton of material about self-joined and hierarchical SQL data, but ... I don't know I've not found what I expected. I've spent too many hours trying solutions, and searching online.
A link to SQLFiddle.
Here is the basic schema for example:
CREATE TABLE [dbo].[Root] (
[RootID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
[Name] [varchar](50)
)
GO
CREATE TABLE [dbo].[Child] (
[ChildID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
[RootID] [int],
[Name] [varchar](50),
[ParentID] [int]
)
GO
ALTER TABLE [dbo].[Child] WITH CHECK ADD CONSTRAINT [Child_RootID_FK] FOREIGN KEY([RootID])
REFERENCES [dbo].[Root] ([RootID]) ON DELETE SET NULL
GO
ALTER TABLE [dbo].[Child] WITH CHECK ADD CONSTRAINT [Child_ParentID_FK] FOREIGN KEY([ParentID])
REFERENCES [dbo].[Child] ([ChildID])
GO
CREATE TRIGGER [dbo].[Root_TR]
ON [dbo].[Root]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[Child] ([RootID], [Name])
SELECT
I.[RootID],
CONCAT_WS('_', (SELECT [Name] FROM [dbo].[Root] R WHERE R.[RootID] = I.RootID), LVL.n )
FROM INSERTED I
CROSS JOIN (VALUES (1), (2), (3)) AS LVL(n)
END
GO
INSERT INTO [dbo].[Root] ([Name]) VALUES (
'Foo'
)
SELECT * FROM [Root]
SELECT * FROM [Child]
I have the current result:
ChildID
RootID
Name
ParentID
1
1
Foo_1
NULL
2
1
Foo_2
NULL
3
1
Foo_3
NULL
The expected result would be:
ChildID
RootID
Name
ParentID
1
1
Foo_1
NULL
2
1
Foo_2
1
3
1
Foo_3
2
I'm not sure how to achieve this.
I've found a close answer (here) involving usage of SEQUENCE
A solution may be something like:
DROP TRIGGER [dbo].[Root_TR]
GO
CREATE SEQUENCE [dbo].[Sequence] START WITH 1 INCREMENT BY 1
GO
CREATE TRIGGER [dbo].[Root_TR]
ON [dbo].[Root]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
ALTER SEQUENCE [dbo].[Sequence] RESTART
DECLARE #map TABLE ([ID] [int], [Seq] [int])
INSERT INTO [dbo].[Child] ([RootID], [Name])
OUTPUT [inserted].ChildID, NEXT VALUE FOR [dbo].[Sequence] INTO #map
SELECT
I.[RootID],
CONCAT_WS('_', (SELECT [Name] FROM [dbo].[Root] R WHERE R.[RootID] = I.RootID), LVL.n )
FROM INSERTED I
CROSS JOIN (VALUES (1), (2), (3)) AS LVL(n)
UPDATE C
SET C.[ParentID] = CASE
WHEN M.Seq = 1
THEN NULL
ELSE
(SELECT [Id] FROM #map WHERE [Seq] = [Seq] - 1)
END
FROM [dbo].Child C
INNER JOIN #map M ON C.ChildID = M.ID
END
GO
Unfortunately usage of NEXT VALUE FOR is not allowed in a OUTPUT clause.
Error 11720 NEXT VALUE FOR function is not allowed in the TOP, OVER, OUTPUT, ON, WHERE, GROUP BY, HAVING, or ORDER BY clauses.
I cannot relie on [Name] column to perform the UPDATE SET [ParentID] = ... FROM ... JOIN ...
There is a lot of answers regarding SQL self joined table but I can't really find the answer and my knowledge regarding SQL is limited.
I've attempted something like this
CREATE TRIGGER [dbo].[Root_TR]
ON [dbo].[Root]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
ALTER SEQUENCE [dbo].[Sequence] RESTART
DECLARE #map TABLE ([ChildID] [int], [Seq] [int])
DECLARE #i int = NEXT VALUE FOR [Sequence]
INSERT INTO [dbo].[Child] ([RootID], [Name])
OUTPUT [inserted].ChildID, #i AS [Seq] INTO #map
SELECT
I.[RootID],
CONCAT_WS('_', (SELECT [Name] FROM [dbo].[Root] R WHERE R.[RootID] = I.RootID), LVL.n )
FROM INSERTED I
CROSS JOIN (VALUES (1), (2), (3)) AS LVL(n)
DECLARE #xml xml = (SELECT * FROM #map FOR XML AUTO)
PRINT CONVERT(nvarchar(max), #xml)
UPDATE C
SET C.[ParentID] = CASE
WHEN M.Seq = 1
THEN NULL
ELSE
(SELECT [ChildID] FROM #map WHERE [Seq] = [Seq] - 1)
END
FROM [dbo].Child C
INNER JOIN #map M ON C.ChildID = M.ChildID
END
GO
Once again unfortunately the temporary TABLE #map is not filled correctly.
The #i is called once and do not increment for each output row.
ChildID
Seq
10
1
11
1
12
1
Another try was to use a DEFAULT. But I've an error when creating the trigger: "Column name or number of supplied values does not match table definition.". Probably because the OUTPUT clause see more columns available in #map TABLE than the number of columns in the OUTPUT.
CREATE TRIGGER [dbo].[Root_TR]
ON [dbo].[Root]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
ALTER SEQUENCE [dbo].[Sequence] RESTART
DECLARE #map TABLE (
[Seq] [int] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR [Sequence]),
[ChildID] [int]
)
INSERT INTO [dbo].[Child] ([RootID], [Name])
OUTPUT [inserted].ChildID INTO #map
SELECT
I.[RootID],
CONCAT_WS('_', (SELECT [Name] FROM [dbo].[Root] R WHERE R.[RootID] = I.RootID), LVL.n )
FROM INSERTED I
CROSS JOIN (VALUES (1), (2), (3)) AS LVL(n)
DECLARE #xml xml = (SELECT * FROM #map FOR XML AUTO)
PRINT CONVERT(nvarchar(max), #xml)
UPDATE C
SET C.[ParentID] = CASE
WHEN M.Seq = 1
THEN NULL
ELSE
(SELECT [ChildID] FROM #map WHERE [Seq] = [Seq] - 1)
END
FROM [dbo].Child C
INNER JOIN #map M ON C.ChildID = M.ChildID
END
GO
And the last try was to use a #table (I do not distinguish clearly between #x TABLE, TABLE #x, TABLE x). But I want to scope the temporary table to the trigger, and not make the table available globally.
So, this time the TRIGGER is created. But when fired, the error message is Invalid object name 'Sequence'. I don't know why the [Sequence] object is not available in this #table.
CREATE TRIGGER [dbo].[Root_TR]
ON [dbo].[Root]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
ALTER SEQUENCE [dbo].[Sequence] RESTART
CREATE TABLE #map (
[Seq] [int] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR [Sequence]),
[ChildID] [int] NOT NULL
)
INSERT INTO [dbo].[Child] ([RootID], [Name])
OUTPUT [inserted].ChildID INTO #map
SELECT
I.[RootID],
CONCAT_WS('_', (SELECT [Name] FROM [dbo].[Root] R WHERE R.[RootID] = I.RootID), LVL.n )
FROM INSERTED I
CROSS JOIN (VALUES (1), (2), (3)) AS LVL(n)
DECLARE #xml xml = (SELECT * FROM #map FOR XML AUTO)
PRINT CONVERT(nvarchar(max), #xml)
UPDATE C
SET C.[ParentID] = CASE
WHEN M.Seq = 1
THEN NULL
ELSE
(SELECT [ChildID] FROM #map WHERE [Seq] = [Seq] - 1)
END
FROM [dbo].Child C
INNER JOIN #map M ON C.ChildID = M.ChildID
END
GO
So finally I don't have yet any solution to properly link my different levels with their parents.
Any help would be highly appreciated.
Here the complete trigger.
CREATE TRIGGER [dbo].[Root_TR]
ON [dbo].[Root]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #map (
[Seq] [int] PRIMARY KEY NOT NULL IDENTITY(1,1)
[ChildID] [int] NOT NULL
)
INSERT INTO [dbo].[Child] ([RootID], [Name])
OUTPUT INSERTED.ChildID INTO #map
SELECT
I.[RootID],
CONCAT_WS('_', (SELECT [Name] FROM [dbo].[Root] R WHERE R.[RootID] = I.RootID), LVL.n )
FROM INSERTED I
CROSS JOIN (VALUES (1), (2), (3)) AS LVL(n)
UPDATE C
SET C.[ParentID] = CASE
WHEN M.[Seq] = 1
THEN NULL
ELSE
(SELECT [ChildID] FROM #map WHERE [Seq] = M.[Seq] - 1)
END
FROM [dbo].Child C
INNER JOIN #map M ON C.ChildID = M.ChildID
END
GO
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
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
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.
I have something like this
create function Answers_Index(#id int, #questionID int)
returns int
as begin
return (select count([ID]) from [Answers] where [ID] < #id and [ID_Question] = #questionID)
end
go
create table Answers
(
[ID] int not null identity(1, 1),
[ID_Question] int not null,
[Text] nvarchar(100) not null,
[Index] as [dbo].[Answers_Index]([ID], [ID_Question]),
)
go
insert into Answers ([ID_Question], [Text]) values
(1, '1: first'),
(2, '2: first'),
(1, '1: second'),
(2, '2: second'),
(2, '2: third')
select * from [Answers]
Which works great, however it tends to slow down queries quite a bit. How can I make column Index persisted? I have tried following:
create table Answers
(
[ID] int not null identity(1, 1),
[ID_Question] int not null,
[Text] nvarchar(100) not null,
)
go
create function Answers_Index(#id int, #questionID int)
returns int
with schemabinding
as begin
return (select count([ID]) from [dbo].[Answers] where [ID] < #id and [ID_Question] = #questionID)
end
go
alter table Answers add [Index] as [dbo].[Answers_Index]([ID], [ID_Question]) persisted
go
insert into Answers ([ID_Question], [Text]) values
(1, '1: first'),
(2, '2: first'),
(1, '1: second'),
(2, '2: second'),
(2, '2: third')
select * from [Answers]
But that throws following error: Computed column 'Index' in table 'Answers' cannot be persisted because the column does user or system data access. Or should I just forget about it and use [Index] int not null default(0) and fill it in on insert trigger?
edit: thank you, final solution:
create trigger [TRG_Answers_Insert]
on [Answers]
for insert, update
as
update [Answers] set [Index] = (select count([ID]) from [Answers] where [ID] < a.[ID] and [ID_Question] = a.[ID_Question])
from [Answers] a
inner join [inserted] i on a.ID = i.ID
go
You could change the column to be a normal column and then update its value when you INSERT/UPDATE that row using a trigger.
create table Answers
(
[ID] int not null identity(1, 1),
[ID_Question] int not null,
[Text] nvarchar(100) not null,
[Index] Int null
)
CREATE TRIGGER trgAnswersIU
ON Answers
FOR INSERT,UPDATE
AS
DECLARE #id int
DECLARE #questionID int
SELECT #id = inserted.ID, #questionID = inserted.ID_question
UPDATE Answer a
SET Index = (select count([ID]) from [Answers] where [ID] < #id and [ID_Question] = #questionID)
WHERE a.ID = #id AND a.ID_question = #questionID
GO
NB* This is not fully correct as it wont work correctly on UPDATE as we wont have the "inserted" table to reference to get the ID and questionid. There is a way around this but i cant remember it right now :(
Checkout this for more info
Computed columns only store the formula of the calculation to perform. That is why it will be slower when querying the computed column from the table. If you want to persist the values to an actual table column, then you are correct about using a trigger.