Welcome to Appsloveworld, In this Post of SQL Server, we will learn to creating and executing stored procedures with output parameters.
Now, before reading this article, I strongly recommend reading our last article.In this post, we have discussed how to create stored procedures with input parameters.
In this post, we will learn how to create a stored procedure with an output parameter.
For creating a stored procedure with an output parameter. We use the keywords Out or Output.
we have a database table Company_Customer. Now we are about to create a stored procedure which gives us the customer count by salary.
CREATE TABLE [dbo].[Company_Customer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CustomerName] [nvarchar](150) NOT NULL,
[CustomerCity] [nvarchar](500) NOT NULL,
[CustomerSalary] [decimal](18, 2) NOT NULL,
)
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (4, 'Olivia', 'New York', CAST(1000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (5, 'Amelia', 'Paris', CAST(2000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1012, 'Ashok', 'New Delhi', CAST(2000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1014, 'George', 'Tokyo', CAST(1000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1015, 'Marry', 'Moscow', CAST(2000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1016, 'Alfie', 'Dubai', CAST(5000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1019, 'Neeraj Singh', 'Banglore', CAST(6000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1020, 'Oliver', 'Singapore', CAST(40000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1022, 'Noah', 'Paris', CAST(5000.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Company_Customer] ([Id], [CustomerName], [CustomerCity], [CustomerSalary]) VALUES (1023, 'Marry', 'Barcelona', CAST(2000.00 AS Decimal(18, 2)))
GO
If you look at stored procedure that we have here,spgetcustomercountbysalary,this procedure has got two parameters @salary and @customercount.
And if you look at the differences between these two parameters @CustomerCount has got output Keywood, whereas @salary doesn’t have it.
Create Procedure spgetcustomercountbysalary
@Salary decimal,
@CustomerCount int Output
as
Begin
Select @CustomerCount = COUNT(Id)
from Company_Customer
where CustomerSalary >= @Salary
End
How To Declare Input-Output Parameters Stored Procedure?
Output keyword indicates that this @CustomerCount is an output parameter and @salary is an input parameter, by default because it doesn’t have the output keyword.
if you look at the procedure definition itself, all we are doing is, we are passing value in the @salary parameter.
For example, if you pass in 2000, as the salary, what this query is going to do is it’s going to count, from Company_Customer table how many customers are there, who’s salary is greater then 2000. And then whatever count we’re getting, we’re using that count to initialize this output parameter.
How to execute stored procedure with input and output parameters in sql server?
Declare @CustomerCount int
Execute spgetcustomercountbysalary 1000, @CustomerCount output
Print @CustomerCount
To execute a procedure with the output parameter. It’s slightly different.
You know that whole procedure is accepting two parameters,First is the @salary parameter and the other one is the @CustomerCount. @salary is an input parameter and @CustomerCount is an output parameter.
Now obviously input parameter means you have to pass something to the stored procedure, whereas the output parameter will return something back to you.
Now when a stored procedure returns something back to you, you have to hold it somewhere obviously in a variable.
That’s why you first create a variable to receive the value. So I have created a variable called @CustomerCount and notice the data type of this the variable should match the data type of your output parameter because essentially we get a value of this data type back.
So if we need a variable, to hold the value that is going to come out of the stored procedure.So that’s why we are creating a variable of an integer data type.
And then when we actually execute the stored procedure.and passing the value for salary.
And then what does this query going to do?
It’s going to count the number of customers who have a salary greater than the parameter value and then it’s going to initialize the output parameter.
so we are passing in a variable which is going to receive that count in this case @CustomerCount receives the value and then finally we print that value.
The post Create Stored procedure with Output and Input parameters in SQL appeared first on Software Development | Programming Tutorials.
Read More Articles
- Linq to SQL Group by and Sum in Select | Linq To SQL Group By and Sum
- How send an HTTP POST request to a server from Excel using VBA?
- What is Difference between where and having clauses in SQL server
- How to Use EXCEPT Operator with an example in Sql
- How to use merge statement in the SQL server
- How to write Re-runnable SQL server query
- How to create Cursor in sql server with example
- How to generate random data in sql server for performance testing
- How to write subquery in select statement in Sql
- How to Log record changes in SQL server in an audit table
- SQL Server - Align value to all identic IDs
- SSIS File System Task Error while copying files between servers
- Why does SQL Server continues to work after deleting the login for the Virtual Account
- C# / SQL Server: how to recurringly lock / truncate / update table while allowing another user to access data seamlessly
- Why is my SQL UPDATE syntax giving 'ambiguous column name'?
- Is there a performance hit for using MDF SQL Server files instead of "database"?
- SQL - CASE Statement if record is NULL because record doesnt exist in table
- Creating ssas cube in xmla structure
- How to get the PrimaryKey value of the newly added record?
- Statistics and Cardinality Estimation - Why am I seeing this result?
- C# SqlCommand query with update
- Super simple query takes 39 seconds to execute
- Connection timeout in ODBC
- Language difference in full text search for numeric strings
- What do I need to change in my T-SQL pivot query to achieve this specific output?
- How do I use alias in where clause?
- sub query and inner join in SQL
- How is data returned from SQL Server
- DbVisualizer 8.0.12 performs two updates instead of expected one update
- Methods to Accelerate Read From a Large Table
- Connect directly through an instance in C#
- SQL Server foreign key constraints issue
- Multiple conditional query to count records in SQL Server
- unresolved reference to object [INFORMATION_SCHEMA].[TABLES]
- SQL Server: is it possible to get data from another SQL server without setting linked server?
- .NET Core - Different spatial / geographic results produced in IEnumerable vs IQueryable
- How to split multiple strings and insert SQL Server FN_SplitStr
- How can I get percentage of each answer in sql?
- Is "IF NOT UPDATE(column)" valid syntax?
- Read child node along with its parent attribute from XML in SQL server
- Function returning data to client error
- SQL IN clause with AND logic in it
- Deadlock on indexed view
- Multiple Running Totals with Group By
- Alternatives to Red Gate SQL Comparison SDK?
- Finding subfolders of a file path from table of file paths using SQL Server "LIKE" function
- SQLException: this driver is not configured for integrated authentication tomcat
- How can I return datetime constant with datetime type in SQL Server?
- colmn_name UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE
- AWS RDS SQL Server failover really slow
- Finding related XML elements filtering on attribute from current element in XPath
- Conditional Filegroup File script in Visual Studio 2010 database project
- NLog - DDL for Log Table and Setting the ConnectionString Programmatically
- SSIS - truncate table when other table contains data with certain value
- SSIS-- Archive Flat File Task Creating Duplicate Files
- Row and column total in dynamic pivot in MS SQL Server 2008 my questions is row total and columns total) for all products when add
- How to see the output of a query which is executed remotely from mysql command line tool?
- Pivot sql with totals
- How do I create a multiple-table check constraint?
- How do I create and set fields for insert_date and last_modified_date in sql server 2008?
- SQL Server / SSIS - Dynamic T-SQL, NVARCHAR(MAX) Difference
- T-SQL auto increment identity?
- Linq insert on primary key field that is autosync
- Find unmatched data in SQL
- SQL Server - Rows to Columns without Aggregation
- how to get date from CDBVariant?
- SQL Server: Comparing against next X in group
- How can I update various sql columns based on another column of the same row?
- Occasional Exceptions: "A network-related or instance-specific error occurred while establishing a connection to SQL Server"
- Update properties in SQL Json fields with nested objects
- Creating a sqlGeography LINESTRING using .NET
- SQL Select the Columnid with a max column group by one column
- SSIS - Getting latest record of rows
- How to rename items by assigning sequential number?
- Pivot transactions to metrics
- Entity Framework connection pooling: how to inject UserId into SQL Servers session_context?
- How to identify and redact all instances of a matching pattern in T-SQL
- SQL Server for xml path add attributes and values
- Converting string from MSSQL to MySQL
- SSMS extensibility/addin - get current database and server
- Extracting username alone from an email address list
- Performance issue related to using WHERE clause
- Sequential GUID's in CodeFluent
- SQL Split Island On Criteria
- Upgrading SQL 2000 32-bit to SQL 2008 64-bit
- Joining tables based on a datetime, but the datetime value can vary within 5 minutes
- SSIS Script Task not working in Visual Studio 2010, Exception has been thrown by the target of an invocation
- using a SqlConnection in C++ / .NET
- Grouping and Returning Zero if no records are found
- SQL Server 2016 experiences insufficient memory or sessions exceeds the maximum allowed in the server
- Union all with group by in sql: not contained in either an aggregate function or the GROUP BY
- How to calculate the difference in revenue for 2 specific periods from data in a single table?
- Modify Return Value of SELECT-Statement (TSQL) [Optimizing query]
- Consolidating Queries
- Use select statement results in while loop
- Dirty Reads in SQL Server AlwaysOn
- Select the occurrence order of the same record next to each record in SQL Server database
- SQL Aggregate function based on 1 column and display the remaining
- SQL trigger not working in Azure Elastic DB
- CTE for Count the Binary Tree nodes
- Quick way to backup SQL SP and Functions?
- Is there any ways to apply where clause in result of stored procedure?
- Count successive weeks in SQL Server
- Conditional SQL Where Clause returning different rows
- SQL Server INSERT, Scope_Identity() and physical writing to disc
- SQL PIVOT on Date Range
- How to get records if value is null with two meanings in SQL Server?
- Solr / SolrNet - Using wildcards for letter by letter search
- How to update a table while using it at the same time?
- Query to loop through one table and insert incrementally by group into another
- SQL - Get Records within Date Range using 2 tables (Date Range/Hours given)
- Calling Saved Powershell Script in SSIS
- SSRS : How to repeat header row of a table on each page that is embedded in a LIST?
- Load Excel to table in SQL
- condition in the stored procedure for the search of date is not functioning
- Creating a View from an Aggregated Self-Join
- Calculate the user account balance from two tables
- SQL Procedure Getting Error
- 1:1 Foreign Key Constraints
- DataReader Behaviour With SQL Server Locking
- Convert row to column in SQL Server does not work?
- Is it possible to debug SQLServer stored procedure using JetBrains DataGrip?
- EF4 - The selected stored procedure returns no columns
- Hibernate+SQLServer / Batch insert only the new records
- How to have Dapper iterate a stored procedure for inserts?
- Detect SQLServer features from ADO.net
- Azure SQL: Cannot execute as the database principal because the principal [USERNAME] does not exist
- SQL Server Management Studio - history of commands run
- How to use common table expression in a dynamic SQL
- Search for a matching string within a group based on a keyword
- How can I prevent divide-by-zero errors in a Stored Procedure?
- Strip Out Characters
- How to use split in SQL Server?
- Invalid column in select list with group by in SQL Server
- BLOB files in SQL-database as chunk
- Hot to use group by dateime with a gap of 2 seconds?
- Incorrect syntax near the keyword 'with' in stored procedure when using OPENJSON
- Insert System date in dd/mm/yyyy hh:mi:ss format
- "Error in TypeData" errors when using Backup-SqlDatabase in Powershell
- SQL Server - grant create table to schema owner
- Check and compare column values in sql server table
- SQL using DISTINCT with INNER JOIN
- Create and Pass a Table-Valued Parameter in a Single Line
- SQL-Aggregate Timeseries Table (HourOfDay, Val) to Average Value of HourOfDay by Weeekday (fi. Avg of Mondays 10:00-11:00, 11:00-12:00,...,Tue...)
- Get non existence arguments of SQL IN operator
- Dynamically Create tables and Insert into it from another table with CSV values
- If value is true update some columns, if not update anothers
- A very big size of tempdb
- SSIS Package FTP Task Error: Directory is not specified in the file connection manager "User::ProcessingFileLocation"
- Can you pass a variable into the interval of DATEDIFF
- Can option "WITH RECOMPILE" be used to reduce timeouts from blocking?
- How to detect SqlServer connection leaks in a ASP.net applications?
- How to prevent SQL injection in Select Insert?
- Practical Development with VS2012, SSDT, and TFS
- Dropping multiple tables at once
- High Paging file % Usage while memory is not full
- How to construct the logic in this SQL WHERE clause?
- How to get SQL Server FOR XML to format float efficiently
- Create a value adding two columns together
- T-SQL LIKE with escaped characters