Stored procedure INSERT INTO with different column count - sql-server

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)

Related

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

Output inserted row from CTE

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

Error occurred in executing Table type parameter

I am trying to insert data into table using BizTalk with below code. But I am facing error as "Procedure or function Emp_Details has too many arguments specified."
Could someone help me out to solve the same?
ALTER PROCEDURE [dbo].[Emp_Details]
(#InsertDetails InsertDetailsType readonly)
AS
Begin
Truncate table [dbo].[Emp_Details]
INSERT INTO [dbo].[Emp_Details]
(
[NAME],
[DESCRIPTION],
[EMPID]
)
select
[NAME],
[DESCRIPTION],
[EMPID]
from #InsertDetails;
Begin
if exists(select 1 from [dbo].[Emp_Details]where NAME='Raul')
Delete from [Emp_Details]where NAME='Raul'
End
end
Reposting the same sample code used previously for reference.
USE <Database>
GO
/* This is a template table */
CREATE TYPE Emp_Details AS TABLE
( [Name] VARCHAR(100)
, [Description] VARCHAR(100)
, [Address] VARCHAR(100));
GO
/* The following is your Table Emp_Details which you must be having already*/
CREATE TABLE Emp_Details
( [Name] VARCHAR(100)
, [Description] VARCHAR(100)
, [Address] VARCHAR(100));
GO
/* Consider this as your Input Data i.e CSV file or Excel (Note: I have created a table for sample)*/
CREATE TABLE Emp_Details1
( [Name] VARCHAR(100)
, [Description] VARCHAR(100)
, [Address] VARCHAR(100));
GO
INSERT INTO Emp_Details1 VALUES ('John','Test','123')
INSERT INTO Emp_Details1 VALUES ('John1','Test1','1234')
INSERT INTO Emp_Details1 VALUES ('John2','Test2','1235')
GO
SELECT * FROM Emp_Details
/* Declare a variable that references the type. So when you reference a `TYPE` it takes the table template which we created previously*/
DECLARE #Emp AS Emp_Details;
/* Add data to the table variable. In your case push the data that you get into the #Emp */
INSERT INTO #Emp ([Name], [Description], [Address])
SELECT [Name], [Description], [Address]
FROM Emp_Details1;
/* Pass the table variable data to a stored procedure. */
EXEC [dbo].[Insert_Deatils] #Emp;
GO
SELECT * FROM Emp_Details

Execution plan showing type conversion warning - ON Cond columns

Getting Type conversion in Expression ..... may affect "CardinalityEstimate" in query pan choice.
The both tables T1 and T2 having clustered indexes.
How to overcome of warning?
CREATE TABLE T1
(
KEY INT IDENTITY(1,1) NOT NULL,
CODE VARCHAR(50),
DESCRIPTION VARCHAR(100),
EXTERNAL_KEY VARCHAR(15),
FLAG BIT
)
INSERT INTO T1 VALUES(1,'ASS','DESC','NULL',0)
INSERT INTO T1 VALUES(1,'ASS1','DESC','45213',1)
INSERT INTO T1 VALUES(1,'ASS2','DESC','NULL',1)
INSERT INTO T1 VALUES(1,'ASS3','DESC','NULL',0)
INSERT INTO T1 VALUES(1,'ASS4','DESC','56321',1)
CREATE TABLE T2
(
KEY INT IDENTITY(1,1) NOT NULL,
CODE VARCHAR(50),
DESCRIPTION VARCHAR(100),
EXTERNAL_KEY NUMERIC(14,0)
)
INSERT INTO T2 VALUES(1,'DSA','DESC',51256)
INSERT INTO T2 VALUES(1,'DSA1','DESC',45213)
INSERT INTO T2 VALUES(1,'DSA2','DESC',51256)
INSERT INTO T2 VALUES(1,'DSA3','DESC',56321)
Actual Query:
SELECT T1.KEY,T1.FLAG,T2.KEY, FROM T2 INNER JOIN T1 ON
CAST(NULLIF(RTRIM(T1.EXTERNAL_KEY),'') AS NUMERIC(14,0)) = T2.EXTERNAL_KEY
WHERE T1.EXTERNAL_KEY IS NOT NULL
There are a few issues with your Sample data as well as the query. KEY INT IDENTITY(1,1) NOT NULL should be changed to [KEY] NOT NULL Or Do not insert into the Identity column INSERT INTO T1 VALUES('ASS','DESC','NULL',0) Also you are not inserting DB NULL but Text null when you enclosed 'NULL' with single quotes. for this. The below code should work
SELECT T1.[KEY],T1.FLAG,T2.[KEY]
FROM T2
INNER JOIN T1
ON NULLIF(T1.EXTERNAL_KEY ,'NULL')=T2.EXTERNAL_KEY
WHERE T1.EXTERNAL_KEY IS NOT NULL
However I think you want NULL to be NULL and Not text so please change your insert from INSERT INTO T1(CODE,DESCRIPTION,EXTERNAL_KEY,FLAG) VALUES('ASS','DESC','NULL',0) to `INSERT INTO T1(CODE,DESCRIPTION,EXTERNAL_KEY,FLAG) VALUES('ASS','DESC',NULL,0)
Sample Data
IF OBJECT_ID('tempdb..#T1') IS NOT NULL
DROP TABLE #T1
IF OBJECT_ID('tempdb..#T2') IS NOT NULL
DROP TABLE #T2
CREATE TABLE #T1
(
[KEY] INT IDENTITY(1,1) NOT NULL,
CODE VARCHAR(50),
DESCRIPTION VARCHAR(100),
EXTERNAL_KEY VARCHAR(15),
FLAG BIT
)
GO
INSERT INTO #T1(CODE,DESCRIPTION,EXTERNAL_KEY,FLAG) VALUES('ASS','DESC',NULL,0)
INSERT INTO #T1(CODE,DESCRIPTION,EXTERNAL_KEY,FLAG) VALUES('ASS1','DESC','45213',1)
INSERT INTO #T1(CODE,DESCRIPTION,EXTERNAL_KEY,FLAG)VALUES('ASS2','DESC',NULL,1)
INSERT INTO #T1(CODE,DESCRIPTION,EXTERNAL_KEY,FLAG)VALUES('ASS3','DESC',NULL,0)
INSERT INTO #T1(CODE,DESCRIPTION,EXTERNAL_KEY,FLAG)VALUES('ASS4','DESC','56321',1)
CREATE TABLE #T2
(
[KEY] INT IDENTITY(1,1) NOT NULL,
CODE VARCHAR(50),
DESCRIPTION VARCHAR(100),
EXTERNAL_KEY NUMERIC(14,0)
)
GO
INSERT INTO #T2 (CODE,DESCRIPTION,EXTERNAL_KEY) VALUES('DSA','DESC',51256)
INSERT INTO #T2 (CODE,DESCRIPTION,EXTERNAL_KEY)VALUES('DSA1','DESC',45213)
INSERT INTO #T2 (CODE,DESCRIPTION,EXTERNAL_KEY)VALUES('DSA2','DESC',51256)
INSERT INTO #T2 (CODE,DESCRIPTION,EXTERNAL_KEY)VALUES('DSA3','DESC',56321)
Code
SELECT #T1.[KEY],#T1.FLAG,#T2.[KEY]
FROM #T2
INNER JOIN #T1
ON NULLIF(#T1.EXTERNAL_KEY ,NULL)=#T2.EXTERNAL_KEY
WHERE #T1.EXTERNAL_KEY IS NOT NULL

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