Output inserted row from CTE - sql-server

I have a CTE and I need to populate that CTE with the row that has been inserted.
I tried using temp table.
I am not sure how to create temp table within CTE and fill CTE.
This is what I have tried:
WITH RESULT AS
(
DECLARE #INSERTOUTPUT1 TABLE
(
BOOKID INT,
BOOKTITLE NVARCHAR(50),
MODIFIEDDATE DATETIME
);
-- INSERT NEW ROW INTO BOOKS TABLE
INSERT INTO BOOKS
OUTPUT INSERTED.* INTO #INSERTOUTPUT1
VALUES(101, 'ONE HUNDRED YEARS OF SOLITUDE', GETDATE());
SELECT * FROM #INSERTOUTPUT1
)
SELECT * FROM RESULT
Below is the schema for the table:
DROP TABLE dbo.Books;
CREATE TABLE dbo.Books
(
BookID int NOT NULL PRIMARY KEY,
BookTitle nvarchar(50) NOT NULL,
ModifiedDate datetime NOT NULL
);

you can't have the declare statement inside the CTE. It should be separate statement. Not sure what you wanted the CTE there for ? but there isn't a need for CTE
DECLARE #INSERTOUTPUT1 TABLE
(
BOOKID INT,
BOOKTITLE NVARCHAR(50),
MODIFIEDDATE DATETIME
);
INSERT INTO Books
OUTPUT INSERTED.* INTO #INSERTOUTPUT1
VALUES(101, 'ONE HUNDRED YEARS OF SOLITUDE', GETDATE());
select *
from #INSERTOUTPUT1

Related

Stored procedure INSERT INTO with different column count

I have a stored procedure and I am trying to insert some data into a temporary table. However, the stored procedure only contains 3 of these columns (col1 through col3), and I am trying to update one and have the last one auto-incremented.
DECLARE #customCol VARCHAR(12)
CREATE TABLE #table
(
col1 VARCHAR(50),
col2 INT,
col3 INT,
customCol VARCHAR(12),
rowNumber INT PRIMARY KEY IDENTITY
)
INSERT INTO #table (col1, col2, col3, customCol, rowNumber)
EXEC sp #var1, #var2
UPDATE #table
SET customCol = #customCol
WHERE rowNumber = (SELECT COUNT(*) FROM #table)
My issue is that whenever I try this, I get the error shown below
Column name or number of supplied values does not match table definition.
I understand that this is because the stored procedure only contains 3 columns and is missing 2 other values, any tips on how I can adjust my query to fix this problem?
Just specify three columns in the insert statement and use IDENTITY(1,1) instead of IDENTITY
--Create tables
CREATE TABLE #table (
col1 VARCHAR(50),
col2 INT,
col3 INT,
customCol VARCHAR(12),
rowNumber INT PRIMARY KEY IDENTITY(1,1)
)
--Insert into first temp table
INSERT INTO #table (col1, col2, col3) EXEC Sp #var1,#var2
UPDATE #table SET customCol = #customCol WHERE rowNumber = (SELECT MAX(rowNumber) FROM #table2)

Auto increment column each time 1,2,3 SQL server

I have temp table each time store 100 values based on a specific condition.
I need Slno as 1,2,3,4 ...100 each time query executes .
If I use below syntax's, the 'Slno' is taking some other numbers
create table #temptable
(Slno INT IDENTITY(1,1) NOT NULL ,
Name varchar(50)
)
create table #temptable
(Slno int IDENTITY(1,1) PRIMARY KEY ,
Name varchar(50)
)
Please help if there is a way out without using Rank()?
You need to create an IDENTITY column as follows:
Syntax:
CREATE TABLE (
ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
...
);
It should be
Identity(seed,increment)
Here you go:
CREATE TABLE #temptable
(Slno INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Name varchar(50)
)
Example:
INSERT INTO #temptable (Name) Values ('ABC')
INSERT INTO #temptable (Name) Values ('ABhshC')
INSERT INTO #temptable (Name) Values ('ABQRAC')
INSERT INTO #temptable (Name) Values ('ABhsAERAYRHAERhC')
SELECT * FROM #temptable
Results:
Slno Name
1 ABC
2 ABhshC
3 ABQRAC
4 ABhsAERAYRHAERhC

Update third table when data updated on sql view

I have got thease three tables:
CREATE TABLE tblEmployee1
(
Id int Primary Key,
Name nvarchar(30),
Gender nvarchar(10),
DepartmentId int
)
CREATE TABLE tblDepartment1
(
DeptId int Primary Key,
DeptName nvarchar(20)
)
CREATE TABLE tblEmployee
(
Id int Primary Key,
Name nvarchar(30),
Gender nvarchar(10),
DepartmentId int,
DeptName nvarchar(20)
)
Two of them are joined by a view:
Create view ViewEmployeeDetails1
as
Select Id, Name, Gender,DepartmentId, DeptName
from tblEmployee1
join tblDepartment1
on tblEmployee1.DepartmentId = tblDepartment1.DeptId
I have created the trigger so that when the view is updated
with data trigger fires and update the third table (tblEmployee) with data in the view wihout duplicate record.
Trigger dosent seem to insert values on to the tblEmployee when the view is updated. Can you please help me with the trigger dont know where it's going
worng My trigger is below Thanks in advance.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Update_Employee]
ON dbo.ViewEmployeeDetails1
INSTEAD OF UPDATE
AS
BEGIN
insert into dbo.tblEmployee
([Id], [Name], [Gender], [DepartmentId], [DeptName])
SELECT i.[Id],i.[Name], i.[Gender], i.[DepartmentId], i.[DeptName]
FROM dbo.ViewEmployeeDetails1 t
INNER JOIN i
ON t.Id = i.Id
WHERE i.Id IS NOT NULL
end
There is no DeptName in the table, so you would seem to want:
insert into dbo.tblEmployee ([Id], [Name], [Gender], [DepartmentId])
SELECT i.[Id], i.[Name], i.[Gender], i.[DepartmentId]
FROM inserted i
WHERE i.Id IS NOT NULL
end;

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

How to Declaring scalar table in sql?

How to declare one element table so it can be used in future queries?
DECLARE #Emp TABLE
(
ID BIGINT NULL,
CompanyID BIGINT NULL
)
INSERT INTO #EMP
SELECT ID,CompanyID FROM Emp WHERE PIN = 123
SELECT COMPANYID FROM COMPANY WHERE ID = #Emp.CompanyID
You can not. A table per definition contains a (possibly) unlimited number of elements. However, you can always do something like this:
DECLARE #CompanyID BIGINT
SET #CompanyID = (SELECT TOP 1 CompanyID FROM #Emp WHERE ...)
By the way, the following line is not correct, as the WHERE clause is incomplete.
SELECT COMPANYID FROM COMPANY WHERE #Emp.CompanyID
If you intention is to create a table variable that will only store a maximum of one row, you can do it like this:
DECLARE #Emp TABLE
(
ID BIGINT NULL,
CompanyID BIGINT NULL,
Lock char(1) not null default 'X' primary key check(Lock='X')
)
INSERT INTO #EMP (ID,CompanyID)
SELECT ID,CompanyID FROM Emp WHERE PIN = 123
Because the table's primary key is constrained to only one possible value, logically there can't be more than one row.

Resources