Persisted computed column with subquery - sql-server

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.

Related

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

How do I populate a table that contains only an identity column?

Consider the following table
CREATE TABLE [dbo].[Numbers]
(
[Id] [INT] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
How do I populate it?
If I add a column (text nchar(20) say) then I can populate it with:
insert into numbers (text) values ('')
but if there are no other columns besides the identity, what do I do?
insert into numbers ( ) values ( )
This throws an error
Incorrect syntax near ')'.
I want to use this for a find the missing sequence number problem.
Specify DEFAULT VALUES:
INSERT INTO dbo.Numbers DEFAULT VALUES;
Or even you can use SET IDENTITY_INSERT:
SET IDENTITY_INSERT YourTable ON;
GO
INSERT INTO YourTable (IdentityColumn) VALUES
(1),
(2),
(3);
GO
SET IDENTITY_INSERT YourTable OFF;
Sample:
CREATE TABLE [dbo].[Numbers](
[Id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY];
DECLARE #Start INT=1;
DECLARE #End INT=100;
SET IDENTITY_INSERT [dbo].[Numbers] ON;
WITH Gen AS (
SELECT #Start AS Num
UNION ALL
SELECT Num + 1 FROM Gen WHERE Num + 1 <= #End
)
INSERT INTO [dbo].[Numbers] (Id)
SELECT Num
FROM Gen
OPTION (maxrecursion 100);
SET IDENTITY_INSERT [dbo].[Numbers] OFF;
SELECT *
FROM [dbo].[Numbers];

How to show only one row

I have this table structure and the sample data as well. I want to get only one row of the data. But instead it is giving me rows equal to it's child records.
--DROP TABLE [Detail];
--DROP TABLE [Master];
--CREATE TABLE [Master]
--(
--ID INT NOT NULL PRIMARY KEY,
--Code VARCHAR(25)
--);
--INSERT INTO [Master] VALUES (1, 'CASH');
--INSERT INTO [Master] VALUES (2, 'CASH');
--CREATE TABLE [Detail]
--(
--ID INT NOT NULL PRIMARY KEY,
--MasterID INT,
--DrAmount Numeric,
--CrAmount Numeric,
--CONSTRAINT FK_MASTER FOREIGN KEY (MasterID)
--REFERENCES [Master](ID)
--);
--INSERT INTO [Detail] VALUES (1, 1, '2200', NULL);
--INSERT INTO [Detail] VALUES (2, 1, NULL, '3200');
--INSERT INTO [Detail] VALUES (3, 1, '1000', NULL);
--INSERT INTO [Detail] VALUES (4, 2, NULL, '3200');
--INSERT INTO [Detail] VALUES (5, 2, '3200', NULL);
Here is the query and result:
SELECT [MASTER].[Code], [DETAIL].[MasterID], [DETAIL].[CrAmount]
FROM [MASTER], [DETAIL]
WHERE [MASTER].[ID] = [DETAIL].[MasterID]
Looks like you need GROUP BY and as #HoneyBadger suggests, it would be better to use the modern explicit join syntax - it is much more clear:
select m.code, d.masterid, sum(d.cramount) amount
from [master] m
join[detail] d on m.[id] = d.[masterid]
group by m.code, d.masterid
Result:
code masterid amount
CASH 1 3200
CASH 2 3200

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.

TRIGGER AFTER INSERT SELECT MIN(COUNT) insert ID

I'm trying to create a trigger after an insert on the eventss table. The trigger should select the Bcoordinator_ID from the bookingCoordinator table where they have the minimum number of occurrences in the eventss table.
Here's my table data followed by the trigger. It doesn't like the minCount in the values, I think it's looking for and int.
DROP TABLE eventsBooking
CREATE TABLE eventsBooking
(
EBK INT NOT NULL IDENTITY(100, 1),
booking_ID AS 'EBK'+CAST( ebk as varchar(10)) PERSISTED PRIMARY KEY,
bookingDate DATE,
Bcoordinator_ID VARCHAR (20),
eventss_ID VARCHAR (20) NOT NULL
)
INSERT INTO eventsBooking
VALUES ('2015-01-07 11:23:00', NULL, 'EVT100');
Eventss table:
EVT INT NOT NULL IDENTITY(100, 1),
eventss_ID AS 'EVT' + CAST(evt as varchar(10)) PERSISTED PRIMARY KEY,
eventsName varchar(50),
noOfStages SMALLINT,
noOfRounds SMALLINT,
eventsDate DATE,
entryFee DECIMAL (7,2),
venue_ID VARCHAR (20) NOT NULL,
judges_ID VARCHAR (20)
INSERT INTO eventss
VALUES ('Swimming Gala 2015', '3', '7', '2015-01-07 09:00:00', '35.00', 'VEN101', 'JUD100');
CREATE TABLE bookingCoordinator
(
BCO INT NOT NULL IDENTITY(100, 1),
Bcoordinator_ID AS 'BCO'+CAST( bco as varchar(10)) PERSISTED PRIMARY KEY,
forename varchar(20) NOT NULL,
familyName varchar(50)
)
INSERT INTO bookingCoordinator VALUES ('Steve', 'Wills');
Trigger:
CREATE TRIGGER TRGinsertJudge
ON [dbo].[eventss]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.eventsBooking (Bcoordinator_ID, bookingDate, Eventss_ID)
VALUES(minCount, getdate(), 100)
SELECT MIN(COUNT(Bcoordinator_ID)) AS minCount
FROM eventsBooking
END
You can't do an aggregation of an aggregation i.e. MIN(COUNT(1))
If you just want the Bcoordinatior_ID with the least counts in eventsBooking, do this
select top 1 bcoordinator_id
from eventsBooking
group by bcoordinator_id
order by count(1) asc
And you don't use VALUES() in an INSERT INTO ... SELECT statement
Also, in your current code, since eventsBooking.bcoordinator_id is always null, you need to join to the actual table of bookingCoordinators to return booking coordinators without any events booked.
So your complete trigger statement should be
INSERT INTO dbo.eventsBooking (Bcoordinator_ID, bookingDate, Eventss_ID)
select
top 1
bookingcoordinator.bcoordinator_id, getdate(), 100
from bookingCoordinator left join eventsBooking
on bookingCoordinator.Bcoordinator_ID = eventsBooking.Bcoordinator_ID
group by bookingcoordinator.bcoordinator_id
order by count(1) asc

Resources