Insert User Defined Data Table in a stored procedure - sql-server

Below is the stored proc i have so far I keep getting this error when executed:
Msg 137, Level 16, State 1, Procedure db_recession_band_dates_save, Line 18
Must declare the scalar variable "#dates".
ALTER PROCEDURE [dbo].[Dates_Save]
#Loc VARCHAR(75),
#dates StartEndDateType READONLY
AS
BEGIN
DECLARE #id int
SELECT #id = MYINTFIELD FROM date_locations
IF #id IS NULL
BEGIN
INSERT INTO db_recession_bands VALUES (#loc)
SET #id = ##IDENTITY
END
INSERT INTO db_recession_band_dates VALUES (#id,#dates)
END

if StartEndDateType is a user defined table type then you treat it as if it were a table.
Change this:
INSERT INTO db_recession_band_dates VALUES (#id,#dates)
Into something like
INSERT INTO db_recession_band_dates (<COLUMN LIST>) -- don't do blind inserts it will hurt you at some point in the future
SELECT #id, <COLUMN LIST>
FROM #dates

Related

Copy column from one table to another table with condition

ALTER PROCEDURE [dbo].[Timesheet_update]
AS
BEGIN
DECLARE #sql2 nvarchar(max), #status nvarchar(1)
SET #sql2 = 'insert into s21022020 (s21_stfno) select m_stfno from master where m_status<>'D''
EXECUTE (#sql2)
END
EXECUTE Timesheet_update
Results in an error:
Msg 207, Level 16, State 1, Line 23
Invalid column name 'D'.
m_status column contain data =D
I don't understand why you feel the need to make this a dynamic SQL - just write the statement directly inside the stored procedure - like this:
ALTER PROCEDURE [dbo].[Timesheet_update]
AS
BEGIN
INSERT INTO s21022020 (s21_stfno)
SELECT m_stfno
FROM master
WHERE m_status <> 'D'
END

How Do I Solve Error "Expects Parameter" for stored procedure

I am getting this error
Msg 201, Level 16, State 4, Procedure sp_GetAllAirports, Line 0 [Batch Start Line 2]
Procedure or function 'sp_GetAllAirports' expects parameter '#AirportID', which was not supplied."
When I run
EXEC sp_GetAllAirports
The following is my stored procedure which shows #AirportID, what could be the issue?
IF OBJECT_ID('sp_GetAllAirports', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sp_GetAllAirports]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_GetAllAirports]
#AirportID INT,
#ICAOCode VARCHAR(4) NULL,
#AirportName VARCHAR(MAX),
#City VARCHAR(MAX),
#Lat DECIMAL(8,3),
#Long DECIMAL (11,3),
#Elevation INT,
#Country NVARCHAR(MAX)
AS
BEGIN TRANSACTION
BEGIN TRY
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--SELECT * FROM tbl_Airports ORDER BY AirportID ASC
SELECT
AirportID, ICAOCode, AirportName, City,
Latitude, Longitude, Elevation, CountryFK
FROM
tbl_Airports
LEFT JOIN
tbl_Countries ON CountryID = tbl_Airports.CountryFK
WHERE
CountryID = tbl_Airports.CountryFK
ORDER BY
AirportID
END TRY
BEGIN CATCH
DECLARE #ErMessage NVARCHAR(MAX),
#ErSeverity INT,
#ErState INT
SELECT
#ErMessage = ERROR_MESSAGE(),
#ErSeverity = ERROR_SEVERITY(),
#ErState = ERROR_STATE()
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
END
RAISERROR(#ErMessage, #ErSeverity, #ErState)
END CATCH
IF ##TRANCOUNT > 0
BEGIN
COMMIT TRANSACTION
END
GO
Your stored procedure is defined to expect arguments (AirportID, ICAOCode, AirportName, City, Lat, Long, Elevation and Country):
CREATE PROCEDURE [dbo].[sp_GetAllAirports]
#AirportID INT,
#ICAOCode VARCHAR(4) NULL,
#AirportName VARCHAR(MAX),
#City VARCHAR(MAX),
#Lat DECIMAL(8,3),
#Long DECIMAL (11,3),
#Elevation INT ,
#Country NVARCHAR(MAX)
AS
...
However, it doesn't use any of them. So you probably just need to remove them:
CREATE PROCEDURE [dbo].[sp_GetAllAirports]
AS
...
Alternatively, make sure the arguments are used in the SP (so it makes sense to expect arguments) and pass values accordingly (sp_GetAllAirports 1234) e.g.:
CREATE PROCEDURE [dbo].[sp_GetAllAirports]
#AirportID INT
AS
....
SELECT AirportID, ICAOCode, AirportName, City, Latitude, Longitude, Elevation, CountryFK
FROM tbl_Airports
LEFT JOIN tbl_Countries ON CountryID = tbl_Airports.CountryFK
WHERE CountryID = tbl_Airports.CountryFK
AND AirportID = #AirportID -- Using first argument here
ORDER BY AirportID
....
Or, finally, give the arguments default values, e.g:
CREATE PROCEDURE [dbo].[sp_GetAllAirports]
#AirportID INT = NULL,
#ICAOCode VARCHAR(4) = 'FOO',
...
AS
...
That way you won't have to explicitly pass any argument values. However, you'll still need to use the arguments to having the arguments make sense in the first place.

SQL stored procedure - table as parameter

I have a database with different tables (all the same structure) where I'd like to run a stored procedure having a parameter that defines which table to query.
I can't seem to figure it out:
CREATE SCHEMA test;
GO
First I created a schema
CREATE TYPE DataType as TABLE (
[datetime] [datetime] NULL,
[testVar] [bigint] NULL)
GO
Then I created the table type
USE [TestDataFiles]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [test].[testing]
(
-- Add the parameters for the stored procedure here
#datetime datetime,
#t DataType READONLY
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
select top(10) *
from #t
where [datetime] > #datetime
END
GO
Then I created the stored procedure.
Exec test.testing #t = 'table.1', #datetime = '2017-01-01'
However when I call it I get the following error:
Msg 206, Level 16, State 2, Procedure test, Line 0 [Batch Start Line 0]
Operand type clash: varchar is incompatible with DataType
Same happens with:
Exec test.testing #t = [table.1], #datetime = '2017-01-01'
I have seen an example where in the procedure between the begin and select you put something like:
INSERT INTO table.1
( datetime, testVar)
But table.1 (or table.2 etc as I have a list of tables) has data and I don't want to change it.
Unless I'm meant to create a dummy table like I did the TYPE?
The examples I've found online havent been useful.
To do that you will need to use dynamic SQL
The basic procedure is to build up a string that will hold the statement you will execute, then execute it
declare #SQL nvarchar(1000)
declare #t as nvarchar (1000)
set #t = 'MyTable'
set #Sql = 'Select * from ' + #t
exec sp_executesql #sql
You have to pass parameter of type DataType. So, create variable of that type and pass it into stored procedure like
declare #table1 DataType
INSERT INTO #table1(datetime, testVar) values (..., ...)
Exec test.testing #datetime = '2017-01-01', #t = #table1

Display the number of rows inserted into a table from an existing table

Please how can display the number of rows inserted into an archive table using Microsoft SQL server 2012 with Stored Procedure. I have my code display below. I ran the code successful, but calling the stored procedure, I got error message says
Msg 8114, Level 16, State 5
Procedure p_moveTransHisttoArchive3a, Line 0 Error converting data type varchar to datetime.
Here is my code:
IF OBJECT_ID(N'Production.p_moveTransHisttoArchive3a', N'P') IS NOT NULL
DROP PROCEDURE Production.p_moveTransHisttoArchive3a;
GO
CREATE PROCEDURE Production.p_moveTransHisttoArchive3a
#FiveDaysAgo DATETIME
AS
SET NOCOUNT ON;
BEGIN
DECLARE #counter INT;
SET #counter = ##ROWCOUNT
INSERT INTO Production.TransactionHistoryArchive
SELECT*
FROM Production.TransactionHistory
WHERE TransactionDate <= #FiveDaysAgo
RETURN #counter --No of rows moved
END;
GO
Here is something close to what you want I think. Why is your inbound parameter named FiveDaysAgo? If you want to always get rows that are older than five days ago that belongs INSIDE the proc, not as a parameter.
CREATE PROCEDURE Production.p_moveTransHisttoArchive3a
#FiveDaysAgo DATETIME
, #RowCount int OUTPUT
AS
set nocount on;
INSERT INTO Production.TransactionHistoryArchive
(
Col1
, Col2
)
SELECT Col1
, Col2
FROM Production.TransactionHistory
WHERE TransactionDate <= #FiveDaysAgo
select #RowCount = ##ROWCOUNT

SQL Server: how to create a stored procedure

I'm learning sql from a book and I'm trying to write a stored procedure but I don't believe that I'm doing it correctly. Is the following way not valid in Microsoft SQL? If not, when is it valid, if ever?
create procedure dept_count(in dept_name varchar(20), out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
I get the following error
Msg 156, Level 15, State 1, Procedure wine_change, Line 1
Incorrect syntax near the keyword 'in'.
T-SQL
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
CREATE PROCEDURE GetstudentnameInOutputVariable
(
#studentid INT, --Input parameter , Studentid of the student
#studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
#StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT #studentname= Firstname+' '+Lastname,
#StudentEmail=email FROM tbl_Students WHERE studentid=#studentid
END
In T-SQL stored procedures for input parameters explicit 'in' keyword is not required and for output parameters an explicit 'Output' keyword is required. The query in question can be written as:
CREATE PROCEDURE dept_count
(
-- Add input and output parameters for the stored procedure here
#dept_name varchar(20), --Input parameter
#d_count int OUTPUT -- Output parameter declared with the help of OUTPUT/OUT keyword
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Statements for procedure here
SELECT #d_count = count(*)
from instructor
where instructor.dept_name=#dept_name
END
GO
and to execute above procedure we can write as:
Declare #dept_name varchar(20), -- Declaring the variable to collect the dept_name
#d_count int -- Declaring the variable to collect the d_count
SET #dept_name = 'Test'
Execute dept_count #dept_name,#d_count output
SELECT #d_count -- "Select" Statement is used to show the output
I think it can help you:
CREATE PROCEDURE DEPT_COUNT
(
#DEPT_NAME VARCHAR(20), -- Input parameter
#D_COUNT INT OUTPUT -- Output parameter
-- Remember parameters begin with "#"
)
AS -- You miss this word in your example
BEGIN
SELECT COUNT(*)
INTO #D_COUNT -- Into a Temp Table (prefix "#")
FROM INSTRUCTOR
WHERE INSTRUCTOR.DEPT_NAME = DEPT_COUNT.DEPT_NAME
END
Then, you can call the SP like this way, for example:
DECLARE #COUNTER INT
EXEC DEPT_COUNT 'DeptName', #COUNTER OUTPUT
SELECT #COUNTER
Try this:
create procedure dept_count(#dept_name varchar(20),#d_count int)
begin
set #d_count=(select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name)
Select #d_count as count
end
Or
create procedure dept_count(#dept_name varchar(20))
begin
select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name
end
CREATE PROCEDURE [dbo].[USP_StudentInformation]
#S_Name VARCHAR(50)
,#S_Address VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Date VARCHAR(50)
SET #Date = GETDATE()
IF EXISTS (
SELECT *
FROM TB_StdFunction
WHERE S_Name = #S_Name
AND S_Address = #S_Address
)
BEGIN
UPDATE TB_StdFunction
SET S_Name = #S_Name
,S_Address = #S_Address
,ModifiedDate = #Date
WHERE S_Name = #S_Name
AND S_Address = #S_Address
SELECT *
FROM TB_StdFunction
END
ELSE
BEGIN
INSERT INTO TB_StdFunction (
S_Name
,S_Address
,CreatedDate
)
VALUES (
#S_Name
,#S_Address
,#date
)
SELECT *
FROM TB_StdFunction
END
END
Table Name : TB_StdFunction
S_No INT PRIMARY KEY AUTO_INCREMENT
S_Name nvarchar(50)
S_Address nvarchar(500)
CreatedDate nvarchar(50)
ModifiedDate nvarchar(50)
Create this way.
Create procedure dept_count(dept_name varchar(20),d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
try this:
create procedure dept_count( #dept_name varchar(20), #d_count INTEGER out)
AS
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
To Create SQL server Store procedure in SQL server management studio
Expand your database
Expand programmatically
Right-click on Stored-procedure and Select "new Stored Procedure"
Now, Write your Store procedure, for example, it can be something like below
USE DatabaseName;
GO
CREATE PROCEDURE ProcedureName
#LastName nvarchar(50),
#FirstName nvarchar(50)
AS
SET NOCOUNT ON;
//Your SQL query here, like
Select FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = #FirstName AND LastName = #LastName
GO
Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (#LastName and #FirstName) and type = parameter type example nvarchar(50) etc.
Source: Stored procedure in sql server (With Example)
To Execute the above stored procedure you can use sample query as below
EXECUTE ProcedureName #FirstName = N'Pilar', #LastName = N'Ackerman';

Resources