<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/" >

<channel>
	<title>Stored Procedures &#8211; SQL Server Guides</title>
	<atom:link href="https://sqlserverguides.com/category/stored-procedures/feed/" rel="self" type="application/rss+xml" />
	<link>https://sqlserverguides.com</link>
	<description>Tutorials on SQL Server</description>
	<lastBuildDate>Wed, 27 May 2026 06:51:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://sqlserverguides.com/wp-content/uploads/2023/10/sqlserverguides-150x150.png</url>
	<title>Stored Procedures &#8211; SQL Server Guides</title>
	<link>https://sqlserverguides.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>SQL Stored Procedure Best Practices</title>
		<link>https://sqlserverguides.com/sql-stored-procedure-best-practices/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Wed, 27 May 2026 05:41:50 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[SQL Stored Procedure Best Practices]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=23424</guid>

					<description><![CDATA[This comprehensive guide serves as a masterclass on SQL stored procedure best practices. Whether you are standardizing database deployment frameworks in an office or refactoring microservices&#8217; data dependencies, this tutorial provides the foundational mechanics, structural design patterns, and optimization strategies necessary. SQL Stored Procedure Best Practices 1. Establishing Structural Integrity and Modular Design Boundaries When ... <a title="SQL Stored Procedure Best Practices" class="read-more" href="https://sqlserverguides.com/sql-stored-procedure-best-practices/" aria-label="Read more about SQL Stored Procedure Best Practices">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This comprehensive guide serves as a masterclass on SQL stored procedure best practices. Whether you are standardizing database deployment frameworks in an office or refactoring microservices&#8217; data dependencies, this tutorial provides the foundational mechanics, structural design patterns, and optimization strategies necessary.</p>



<h2 class="wp-block-heading">SQL Stored Procedure Best Practices</h2>



<h3 class="wp-block-heading">1. Establishing Structural Integrity and Modular Design Boundaries</h3>



<p class="wp-block-paragraph">When engineering database backends, it is highly tempting to treat stored procedures as dumping grounds for multi-thousand-line operational scripts. </p>



<h4 class="wp-block-heading">The Single-Responsibility Rule</h4>



<p class="wp-block-paragraph">If a stored procedure is tasked with auditing a user session, calculating an inventory delta, updating a financial ledger, and sending out transactional metadata triggers all within a single code block, it is structurally flawed. Monolithic procedures are incredibly difficult for relational engines to optimize because the internal branches create highly unpredictable execution flows.</p>



<p class="wp-block-paragraph">Instead, break your operations down into discrete, modular components. Have a parent orchestration procedure manage the transactional boundaries while calling specialized child procedures to handle specific sub-tasks. This clean separation of concerns ensures that engineering leads can isolate and troubleshoot bugs without risking regressions across unrelated business modules.</p>



<h3 class="wp-block-heading">2. Advanced Parameter Engineering and Defending Against Side Effects</h3>



<p class="wp-block-paragraph">Parameters act as the contract between your calling application and the database engine. Crafting these interfaces requires precise syntax and strict data governance to ensure maximum execution stability.</p>



<h4 class="wp-block-heading">Strict Data Type Matching</h4>



<p class="wp-block-paragraph">One of the most insidious performance killers in relational databases is an implicit data type conversion. If a table column is defined as a <code>VARCHAR(50)</code> and your stored procedure parameter is declared as an <code>NVARCHAR(50)</code>, the database engine cannot directly compare the two strings. To resolve the conflict, the query optimizer must inject a hidden conversion operator into the execution plan, converting every single row in the column to match the parameter type.</p>



<p class="wp-block-paragraph">This conversion mechanism strips the database engine of its ability to perform high-speed index seek operations, forcing a full table or clustered index scan instead. To prevent this, always cross-reference your database schema and guarantee that stored procedure input and output parameters mirror the exact data types, lengths, and collations of the underlying table columns they interact with.</p>



<h4 class="wp-block-heading">The Strategic Value of Default Parameter Values</h4>



<p class="wp-block-paragraph">When designing robust software interfaces, resilience is paramount. Assigning sensible default values to parameters where applicable allows your stored procedures to gracefully handle omitted arguments from client applications. This practice simplifies API integration and ensures that non-critical parameters—such as sorting orders, page sizes, or optional filtering flags—have safe fallback metrics established directly within the database tier.</p>



<h3 class="wp-block-heading">3. Designing Enterprise-Grade Error Handling and Transaction Controls</h3>



<p class="wp-block-paragraph">In a production environment, errors are an inevitability. How your database code responds to an unexpected failure separates amateur scripts from enterprise-grade software infrastructure.</p>



<h4 class="wp-block-heading">Implementing Structured Error Trapping</h4>



<p class="wp-block-paragraph">Modern database engines provide robust error-trapping constructs through <code>TRY...CATCH</code> blocks. Every single stored procedure that alters data state must encapsulate its logic within a structured exception-handling framework. When an error occurs within the <code>TRY</code> block, control is immediately passed to the <code>CATCH</code> block, preventing unhandled exceptions from bubbling up to the client application in an unsafe state.</p>



<h4 class="wp-block-heading">Defending Transactional Atomicity</h4>



<p class="wp-block-paragraph">When executing multi-statement modifications, safeguarding data integrity requires strict adherence to ACID principles (Atomicity, Consistency, Isolation, Durability). You must manage transactions explicitly, rather than relying on implicit server behaviors.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><td><strong>Transaction State</strong></td><td><strong>Operational Objective</strong></td><td><strong>Core Coding Rule</strong></td><td><strong>Critical Failure Guard</strong></td></tr></thead><tbody><tr><td><strong><code>BEGIN TRANSACTION</code></strong></td><td>Initiates an isolated logical unit of work.</td><td>Declare explicitly after confirming input parameter validity.</td><td>Never open a transaction before long-running non-database tasks.</td></tr><tr><td><strong><code>COMMIT TRANSACTION</code></strong></td><td>Permanently records all modifications to disk.</td><td>Execute as the absolute final statement of a successful <code>TRY</code> block.</td><td>Ensure all internal data checks pass before calling commit.</td></tr><tr><td><strong><code>ROLLBACK TRANSACTION</code></strong></td><td>Reverts all structural modifications to the baseline state.</td><td>Place at the absolute top of the <code>CATCH</code> block layer.</td><td>Verify <code>XACT_STATE()</code> is active before executing a rollback.</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">By checking the internal transaction state (<code>XACT_STATE()</code>) inside the <code>CATCH</code> block, you can safely determine if a transaction is uncommittable and roll it back cleanly. This deterministic error boundary prevents partial updates from corrupting your enterprise ledgers and keeps data blocks unlocked, eliminating cascading application timeouts.</p>



<h3 class="wp-block-heading">4. Maximizing Execution Plan Reusability and Performance Stability</h3>



<p class="wp-block-paragraph">To build blazing-fast database routines, you must design your stored procedures to work seamlessly with the query optimizer’s caching mechanisms.</p>



<h4 class="wp-block-heading">Leveraging Pre-Compiled Execution Plans</h4>



<p class="wp-block-paragraph">One of the primary structural advantages of using stored procedures over raw ad-hoc SQL queries is execution plan reuse. When a stored procedure executes for the first time, the database engine compiles an optimal path for retrieving data and caches it in the server&#8217;s memory buffer pool. Subsequent executions simply reuse this cached plan, eliminating compilation latency and drastically reducing CPU consumption across your database cluster.</p>



<h4 class="wp-block-heading">Mitigating the Perils of Dynamic SQL</h4>



<p class="wp-block-paragraph">Injecting dynamic SQL strings inside a stored procedure via execution commands like <code>EXEC()</code> or <code>EXECUTE IMMEDIATE</code> breaks the core compilation benefits of stored procedures. The database engine treats raw dynamic strings as ad-hoc queries, requiring a fresh compilation plan nearly every time they execute. Furthermore, raw concatenation of dynamic strings opens a massive vector for catastrophic SQL Injection attacks.</p>



<p class="wp-block-paragraph">If dynamic SQL is absolutely mandatory—such as for highly complex, multi-axis search screens—always implement it using parameterized execution commands like <code>sp_executesql</code>. This advanced routine allows the database engine to cache the underlying parameter structure securely, defending your infrastructure against malicious code injection while promoting efficient plan reusability.</p>



<h3 class="wp-block-heading">5. Architectural Memory Governance: The Dangers of Row-by-Row Processing</h3>



<p class="wp-block-paragraph">Relational database engines are engineered from the ground up to process data in massive sets. Despite this fact, a common anti-pattern among application developers migrating to database environments is row-by-row procedural programming.</p>



<h4 class="wp-block-heading">Eliminating Cursors and Loops</h4>



<p class="wp-block-paragraph">Using database cursors or <code>WHILE</code> loops to iterate through rows sequentially is one of the most resource-intensive operations you can write. A loop forces the database engine to perform individual memory fetches, context switches, and locking operations for every single record in the dataset. A cursor processing 100,000 rows will easily run orders of magnitude slower than a clean set-based query.</p>



<p class="wp-block-paragraph">Always refactor procedural loops into declarative, set-based T-SQL logic utilizing standard relational operators such as <code>JOIN</code>, <code>MERGE</code>, and conditional <code>CASE</code> expressions. For instance, if a person encounters a legacy cursor designed to calculate tiered bulk discounts row-by-row, he can easily refactor that logic into a single, highly optimized <code>UPDATE</code> statement driven by an inner join to a reference matrix. This set-based optimization slashes execution times from hours to milliseconds.</p>



<h3 class="wp-block-heading">6. Security Boundaries and Enforcing Minimum Privilege Access</h3>



<p class="wp-block-paragraph">Stored procedures serve as a vital security abstraction layer, serving as a firewall between external networks and your sensitive raw data storage tables.</p>



<h4 class="wp-block-heading">Implementing Schema Abstraction</h4>



<p class="wp-block-paragraph">In a secure enterprise architecture, application service accounts must never be granted direct read or write access to physical database tables. If an application account possesses direct table permissions, a compromise of that account gives an attacker full access to manipulate or exfiltrate your entire corporate data footprint.</p>



<p class="wp-block-paragraph">Instead, deny all direct table access and route every single data interaction through stored procedures. This approach allows security teams to grant application accounts explicit <code>EXECUTE</code> permissions exclusively on specific stored procedures. The application can query data and perform business actions only through these tightly governed gates, creating an immutable security perimeter around your core data infrastructure.</p>



<h4 class="wp-block-heading">Using the <code>WITH EXECUTE AS</code> Clause Safely</h4>



<p class="wp-block-paragraph">By default, a stored procedure runs under the security context of the user calling it. However, scenarios arise where a standard user must perform an action that requires temporary elevated administrative privileges—such as writing to an audited security log table.</p>



<p class="wp-block-paragraph">Utilizing the <code>WITH EXECUTE AS</code> clause allows you to explicitly define the execution context of the procedure, granting it the identity of a specific, highly restricted service principal during its lifecycle. This capability enables you to enforce the principle of least privilege, ensuring that application tiers can perform specialized tasks securely without expanding their global access footprint.</p>



<h3 class="wp-block-heading">7. Operational Best Practices: Code Maintainability and Standards</h3>



<p class="wp-block-paragraph">To ensure your stored procedure libraries remain asset assets rather than technical debt as your engineering organization expands, adopt these industry-proven baseline standards:</p>



<ul class="wp-block-list">
<li><strong>Enforce Clean Naming Conventions:</strong> Never prefix your custom stored procedures with <code>sp_</code>. The <code>sp_</code> prefix is explicitly reserved by the database engine for system stored procedures. When the engine encounters a procedure starting with <code>sp_</code>, it is forced to scan the master database first, incurring unnecessary lookup overhead and introducing potential naming collisions during engine upgrades. Use clear, organizational prefixes such as <code>App_</code>, <code>Core_</code>, or <code>Reporting_</code>.</li>



<li><strong>Disable Unnecessary Metadata Counters:</strong> Always include the <code>SET NOCOUNT ON;</code> statement at the absolute top of your stored procedures. By default, the database engine transmits a network message back to the calling client indicating the exact number of rows affected by every statement within the procedure. In high-transaction environments, these metadata packets create substantial network chatter and can break application object-relational mappers (ORMs). Turning this off improves throughput.</li>



<li><strong>Avoid Star Selections (<code>SELECT *</code>):</strong> Never use wildcard selections inside production code. Explicitly declare every single column required by your query logic. This practice protects your stored procedures from breaking if a DBA adds, modifies, or drops non-related columns from the underlying tables in the future, while minimizing network and memory usage.</li>



<li><strong>Incorporate Comprehensive Code Headers:</strong> Every stored procedure must include a standardized documentation block at the top of the script detailing the author, creation date, modification history, and the business intent of the logic. This establishes clear accountability and speeds up onboarding for future development teams.</li>
</ul>



<h2 class="wp-block-heading">8. Summary and Conclusion</h2>



<p class="wp-block-paragraph">Adhering to SQL stored procedure best practices is a non-negotiable requirement for any serious database engineer or enterprise cloud architect aiming to build modern, performant, and secure data-delivery platforms. </p>



<p class="wp-block-paragraph">By enforcing single-responsibility boundaries, matching data types rigorously, implementing deterministic transaction controls, and completely eliminating row-by-row processing, you empower your organization to process data with unparalleled speed and architectural stability.</p>



<p class="wp-block-paragraph">You may also like the following articles:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-query-optimization-tips/" target="_blank" rel="noreferrer noopener">SQL Query Optimization Tips</a></li>



<li><a href="https://sqlserverguides.com/sql-server-functions-vs-stored-procedures/" target="_blank" rel="noreferrer noopener">SQL Server Functions vs Stored Procedures</a></li>



<li><a href="https://sqlserverguides.com/debug-stored-procedure-in-ssms/" target="_blank" rel="noreferrer noopener">Debug Stored Procedure In SSMS</a></li>



<li><a href="https://sqlserverguides.com/get-stored-procedure-list-in-sql-server-by-modified-date/" target="_blank" rel="noreferrer noopener">Get Stored Procedure List in SQL Server by Modified Date</a></li>



<li><a href="https://sqlserverguides.com/how-to-insert-data-using-stored-procedure-in-sql-server/" target="_blank" rel="noreferrer noopener">How to Insert Data Using Stored Procedure in SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Debug Stored Procedure In SSMS</title>
		<link>https://sqlserverguides.com/debug-stored-procedure-in-ssms/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Thu, 23 Apr 2026 15:53:33 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Debug Stored Procedure In SSMS]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=23325</guid>

					<description><![CDATA[In this comprehensive article, I will share my personal workflow for debugging stored procedures, moving from the native debugger to modern, high-authority techniques. Debug Stored Procedure In SSMS Poorly debugged procedures lead to: By mastering the debugger, you aren&#8217;t just fixing a bug; you are ensuring the reliability of the entire data pipeline. The SSMS ... <a title="Debug Stored Procedure In SSMS" class="read-more" href="https://sqlserverguides.com/debug-stored-procedure-in-ssms/" aria-label="Read more about Debug Stored Procedure In SSMS">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this comprehensive article, I will share my personal workflow for debugging stored procedures, moving from the native debugger to modern, high-authority techniques.</p>



<h2 class="wp-block-heading">Debug Stored Procedure In SSMS</h2>



<p class="wp-block-paragraph">Poorly debugged procedures lead to:</p>



<ul class="wp-block-list">
<li><strong>Performance Drag:</strong> Logic loops that consume excessive CPU.</li>



<li><strong>Data Integrity Issues:</strong> Incorrect calculations that impact the bottom line.</li>



<li><strong>Scalability Bottlenecks:</strong> Code that works for ten rows but fails for ten million.</li>
</ul>



<p class="wp-block-paragraph">By mastering the debugger, you aren&#8217;t just fixing a bug; you are ensuring the reliability of the entire data pipeline.</p>



<h3 class="wp-block-heading">The SSMS Debugging Toolkit: An Overview</h3>



<p class="wp-block-paragraph">Before we start the tutorial, let&#8217;s look at the tools at our disposal. Microsoft has evolved the debugging experience significantly, though it’s important to note where certain features reside.</p>



<h4 class="wp-block-heading">Key Debugging Components</h4>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><td><strong>Tool</strong></td><td><strong>Purpose</strong></td><td><strong>Best Used For</strong></td></tr></thead><tbody><tr><td><strong>Transact-SQL Debugger</strong></td><td>Step-by-step execution</td><td>Granular logic verification</td></tr><tr><td><strong>Locals Window</strong></td><td>Monitor variable values</td><td>Tracking state changes during loops</td></tr><tr><td><strong>Watch Window</strong></td><td>Track specific expressions</td><td>Monitoring complex calculations</td></tr><tr><td><strong>Call Stack</strong></td><td>View the hierarchy of calls</td><td>Nested procedures or triggers</td></tr><tr><td><strong>Breakpoints</strong></td><td>Pause execution at a specific line</td><td>Fast-forwarding to a known problem area</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">My Step-by-Step Tutorial: Debugging Your First Stored Procedure</h3>



<p class="wp-block-paragraph">Let’s walk through the exact process I use when a client, say a healthcare provider, tells me their &#8220;Patient Billing&#8221; procedure is returning null values.</p>



<h4 class="wp-block-heading">Phase 1: Environment Preparation</h4>



<p class="wp-block-paragraph">You never, and I mean <em>never</em>, debug directly in a production environment.</p>



<ol start="1" class="wp-block-list">
<li><strong>Isolate the Environment:</strong> Ensure you are connected to a Development or UAT instance.</li>



<li><strong>Permissions Check:</strong> Debugging requires the <code>sysadmin</code> fixed server role or specific permissions. I always ensure my account has the <code>EXECUTE</code> and <code>VIEW DEFINITION</code> rights, alongside being a member of the <code>db_owner</code> role in the test environment.</li>



<li><strong>The &#8220;Driver&#8221; Script:</strong> Instead of just running the procedure, I write a &#8220;driver&#8221; script in a new query window. This script declares the variables, sets their values, and then calls the procedure.</li>
</ol>



<h4 class="wp-block-heading">Phase 2: Setting Breakpoints</h4>



<p class="wp-block-paragraph">Think of a breakpoint as a &#8220;stop sign&#8221; for your code.</p>



<ul class="wp-block-list">
<li>Find the line where you suspect the logic fails—perhaps a complex <code>JOIN</code> or a <code>WHILE</code> loop.</li>



<li>Click the gray margin to the left of the line number. A red dot will appear.</li>



<li><strong>Pro Tip:</strong> I like to set breakpoints at the very beginning of the <code>BEGIN...END</code> block and right before the final <code>SELECT</code> or <code>RETURN</code>.</li>
</ul>



<h4 class="wp-block-heading">Phase 3: Launching the Debugger</h4>



<p class="wp-block-paragraph">In the toolbar, you’ll see the green &#8220;Play&#8221; button labeled <strong>Debug</strong>.</p>



<ol start="1" class="wp-block-list">
<li>Click <strong>Debug</strong> (or press <code>Alt + F5</code>).</li>



<li>SSMS will switch to the Debugging Layout. If your windows (Locals, Watch, Call Stack) don&#8217;t appear, go to <strong>Debug &gt; Windows</strong> to toggle them on.</li>



<li>The execution will pause at your first breakpoint, highlighted by a yellow arrow.</li>
</ol>



<h4 class="wp-block-heading">Phase 4: Navigating the Logic</h4>



<p class="wp-block-paragraph">This is where the real detective work happens. Use these keyboard shortcuts to move with authority:</p>



<ul class="wp-block-list">
<li><strong>F11 (Step Into):</strong> Use this to follow the execution into a nested stored procedure or function.</li>



<li><strong>F10 (Step Over):</strong> Use this to execute the current line and move to the next without diving into sub-procedures.</li>



<li><strong>Shift + F11 (Step Out):</strong> Use this if you’ve stepped into a long function and want to jump back to the parent procedure.</li>
</ul>



<h3 class="wp-block-heading">Advanced Techniques: Beyond the Basics</h3>



<p class="wp-block-paragraph">Once you are comfortable with stepping through code, you need to use the more sophisticated windows to understand <em>why</em> the bug exists.</p>



<h4 class="wp-block-heading">Monitoring State with the Locals Window</h4>



<p class="wp-block-paragraph">In the <strong>Locals Window</strong>, SSMS automatically lists every variable declared in your procedure and its current value. I watch this like a hawk. If a variable that should hold a &#8220;Customer ID&#8221; suddenly becomes <code>NULL</code> after a specific <code>SELECT</code> statement, I’ve found my culprit.</p>



<h4 class="wp-block-heading">The Watch Window: Your Custom Dashboard</h4>



<p class="wp-block-paragraph">Sometimes the Locals window is too cluttered. I use the <strong>Watch Window</strong> to track specific expressions. For example, if I’m calculating sales tax for a project in Texas, I might add an expression like <code>@SubTotal * 0.0825</code> to the Watch window to see how the value changes in real-time as the <code>@SubTotal</code> is updated.</p>



<h4 class="wp-block-heading">Using the Call Stack for Nested Complexity</h4>



<p class="wp-block-paragraph">In large-scale US financial systems, it’s common for one procedure to call five others. The <strong>Call Stack</strong> is your map. It shows you the path the execution took to reach the current line. If an error occurs deep inside a &#8220;CalculateInterest&#8221; procedure, the Call Stack tells me exactly which &#8220;AccountProcess&#8221; call triggered it.</p>



<h3 class="wp-block-heading">Troubleshooting Common Debugger Issues</h3>



<p class="wp-block-paragraph">Even for experts, the SSMS debugger can be finicky. Here are the three most common hurdles I encounter and how to clear them.</p>



<h4 class="wp-block-heading">1. Firewall Blocks</h4>



<p class="wp-block-paragraph">Many U.S. corporate networks are locked down tight. The SSMS debugger uses RPC (Remote Procedure Call) ports. If you can&#8217;t start a session, your local Windows Firewall or the server&#8217;s firewall is likely blocking the connection.</p>



<ul class="wp-block-list">
<li><strong>Fix:</strong> Work with your SysAdmin to ensure the necessary ports (typically TCP 135 and the dynamic range) are open between your workstation and the SQL Server.</li>
</ul>



<h4 class="wp-block-heading">2. &#8220;The debugger is not enabled&#8221;</h4>



<p class="wp-block-paragraph">Sometimes the debugger simply refuses to start.</p>



<ul class="wp-block-list">
<li><strong>Fix:</strong> Ensure you are using a version of SSMS that matches or is newer than your SQL Server version. Also, verify that you aren&#8217;t trying to debug a script that isn&#8217;t a stored procedure (the debugger works best when wrapped in an <code>EXEC</code> statement).</li>
</ul>



<h4 class="wp-block-heading">3. Performance Overhead</h4>



<p class="wp-block-paragraph">Debugging is &#8220;heavy.&#8221; It places locks and consumes resources.</p>



<ul class="wp-block-list">
<li><strong>Warning:</strong> Running the debugger on a busy server in a Chicago data center can cause &#8220;blocking&#8221; for other users. This is why isolation is your best friend.</li>
</ul>



<h3 class="wp-block-heading">The &#8220;Manual&#8221; Debugging Method (The DBA&#8217;s Secret)</h3>



<p class="wp-block-paragraph">Sometimes, the GUI debugger isn&#8217;t the right tool—especially if you are dealing with a &#8220;heisenbug&#8221; that only appears under heavy load. In these cases, I revert to <strong>Transaction-based Debugging</strong>.</p>



<h4 class="wp-block-heading">The <code>BEGIN TRAN</code> Strategy</h4>



<p class="wp-block-paragraph">This is a high-authority move. I wrap my test execution in a transaction that I never commit.</p>



<ol start="1" class="wp-block-list">
<li><code>BEGIN TRANSACTION</code></li>



<li><code>EXEC MyStoredProcedure @Param1 = 'USA'</code></li>



<li><code>SELECT * FROM TargetedTable -- Check the results</code></li>



<li><code>ROLLBACK TRANSACTION</code></li>
</ol>



<p class="wp-block-paragraph">By using <code>ROLLBACK</code>, I can see exactly what the procedure did to the data without actually making any permanent changes. This is the safest way to &#8220;debug&#8221; the <em>results</em> of a procedure.</p>



<h3 class="wp-block-heading">Comparison: Debugger vs. PRINT vs. Extended Events</h3>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><td><strong>Method</strong></td><td><strong>Level of Detail</strong></td><td><strong>Impact on Server</strong></td><td><strong>Best For</strong></td></tr></thead><tbody><tr><td><strong>SSMS Debugger</strong></td><td>High (Step-by-step)</td><td>High (Blocks execution)</td><td>Complex logic, loops</td></tr><tr><td><strong>PRINT / SELECT</strong></td><td>Low (Point-in-time)</td><td>Low</td><td>Quick variable checks</td></tr><tr><td><strong>Extended Events</strong></td><td>Medium (Event-based)</td><td>Very Low</td><td>Production troubleshooting</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Expert Best Practices for Stored Procedures</h3>



<p class="wp-block-paragraph">To minimize the time you spend debugging, I recommend adopting these development standards used by top-tier US engineering teams:</p>



<ul class="wp-block-list">
<li><strong>Use <code>TRY...CATCH</code> Blocks:</strong> Always wrap your logic. It allows you to catch errors gracefully and log them to a custom <code>ErrorLog</code> table.</li>



<li><strong>Set <code>NOCOUNT ON</code>:</strong> This prevents the &#8220;X rows affected&#8221; messages from interfering with your result sets, which can sometimes confuse debugging tools.</li>



<li><strong>Comment Your Logic:</strong> If you’re writing a 500-line procedure for a logistics firm in Atlanta, your future self will thank you for explaining <em>why</em> a specific <code>WHERE</code> clause exists.</li>



<li><strong>Modularize:</strong> Instead of one giant &#8220;God Procedure,&#8221; break logic into smaller, testable sub-procedures. It is much easier to debug a 20-line procedure than a 2000-line one.</li>
</ul>



<h2 class="wp-block-heading">Conclusion: </h2>



<p class="wp-block-paragraph">Debugging is more than just fixing errors; it’s about understanding the &#8220;soul&#8221; of your data engine. When you can step through a stored procedure in SSMS, monitor the call stack, and predict variable shifts before they happen, you stop being a coder and start being an architect.</p>



<p class="wp-block-paragraph">You may also like the following articles:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/trigger-sql-server/" target="_blank" rel="noreferrer noopener">Trigger SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>While Loop in SQL Server Stored Procedure</title>
		<link>https://sqlserverguides.com/while-loop-in-sql-server-stored-procedure/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Fri, 19 Apr 2024 11:13:57 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[While Loop in SQL Server Stored Procedure]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=21068</guid>

					<description><![CDATA[In this SQL Server tutorial, I will explain the while loop in the SQL Server stored procedure. Whenever I am required to execute complex logic for many records in a table, I use the while loop to avoid writing this logic again and again; I encapsulate this logic into a stored procedure, so whenever I ... <a title="While Loop in SQL Server Stored Procedure" class="read-more" href="https://sqlserverguides.com/while-loop-in-sql-server-stored-procedure/" aria-label="Read more about While Loop in SQL Server Stored Procedure">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this SQL Server tutorial, I will explain the <strong>while loop in the SQL Server stored procedure.</strong></p>



<p class="wp-block-paragraph">Whenever I am required to execute complex logic for many records in a table, I use the while loop to avoid writing this logic again and again; I encapsulate this logic into a stored procedure, so whenever I need it, I just call this procedure.</p>



<p class="wp-block-paragraph">This reduces my time and effort. In this tutorial, I have explained the while loop and stored procedure and how you can encapsulate the while loop within the stored procedure for repetitive tasks or logic that you want to execute repeatedly.</p>



<p class="wp-block-paragraph">You will learn this concept by applying it using real-world examples.</p>



<p class="wp-block-paragraph">So, let&#8217; start,</p>



<h2 class="wp-block-heading">While Loop in SQL Server Stored Procedure</h2>



<p class="wp-block-paragraph">First, you must know what a while loop is and how it works. The while loop in SQL Server executes the block of code repeatedly based on the specified boolean condition.  </p>



<p class="wp-block-paragraph">The while loop runs until the boolean condition becomes false, and as soon as the boolean condition becomes false, the while loop is terminated.</p>



<p class="wp-block-paragraph">The syntax is given below.</p>



<pre class="wp-block-code"><code>WHILE boolean_condition
BEGIN
    -- Statements that you want to execute
END</code></pre>



<p class="wp-block-paragraph">Where,</p>



<ul class="wp-block-list">
<li><strong>boolean_condition:</strong> It is the expression that returns true or false. This condition is evaluated before starting the next iteration.
<ul class="wp-block-list">
<li>If the condition is true, then the block of statements within BEGIN and END is executed,</li>



<li>Otherwise, if the condition is false, it breaks the execution or exits the loop. If any code exists after the END keyword, it begins to execute that code.</li>
</ul>
</li>
</ul>



<p class="wp-block-paragraph">The <strong>BEGIN&#8230;END</strong> section is where you write your SQL statement, query, or whatever operation you want to perform on the database.</p>



<p class="wp-block-paragraph">Now that you know how to use the while loop, let&#8217;s learn about stored procedures. A stored procedure is a way to store the database logic that you want to execute repeatedly.</p>



<p class="wp-block-paragraph">Suppose you have complex database logic that you need to execute usually, so instead of writing this logic whenever required, you keep the logic in something called stored procedure, then call this stored procedure whenever you need that logic.</p>



<p class="wp-block-paragraph">If you have any doubts related to the stored procedure, then you can refresh your knowledge about the stored procedure by reading this tutorial, <a href="https://sqlserverguides.com/create-stored-procedure-in-sql-server/">Create Stored Procedure in SQL Server</a>.</p>



<p class="wp-block-paragraph">Here, we will build a stored procedure to update the inventory, such as the product quantity. So whenever we need to update the product quantity, we will call this stored; that&#8217;s it.</p>



<p class="wp-block-paragraph">First, create a table named Products with columns ID and Quantity which is shown below.</p>



<pre class="wp-block-code"><code>CREATE TABLE Products (
    ID INT PRIMARY KEY,
    Quantity INT
);</code></pre>



<p class="wp-block-paragraph">Insert the 10 different records into the table Products using the query below.</p>



<pre class="wp-block-code"><code>INSERT INTO Products (ID, Quantity) VALUES
(1, 100),
(2, 150),
(3, 200),
(4, 250),
(5, 300),
(6, 350),
(7, 400),
(8, 450),
(9, 500),
(10, 550);</code></pre>



<p class="wp-block-paragraph">View the Products table using the query below.</p>



<pre class="wp-block-code"><code>SLELECT * FROM Products;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" width="740" height="764" src="https://sqlserverguides.com/wp-content/uploads/2024/04/Creating-Products-Table-Before-Creating-While-Loop-in-SQL-Server-Stored-Procedure.jpg" alt="Creating Products Table Before Creating While Loop in SQL Server Stored Procedure" class="wp-image-21073" style="width:356px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/04/Creating-Products-Table-Before-Creating-While-Loop-in-SQL-Server-Stored-Procedure.jpg 740w, https://sqlserverguides.com/wp-content/uploads/2024/04/Creating-Products-Table-Before-Creating-While-Loop-in-SQL-Server-Stored-Procedure-291x300.jpg 291w" sizes="(max-width: 740px) 100vw, 740px" /></figure>
</div>


<p class="wp-block-paragraph">From the above picture, you can see that the Products table contains the records of the 10 products and their quantities.</p>



<p class="wp-block-paragraph">Now, suppose you need to create a stored procedure named <strong>UpdateInventoryQuantity</strong>. This stored procedure should contain a while loop to add the 10 quantities to each product.</p>



<p class="wp-block-paragraph">You can create that kind of stored procedure using the command below.</p>



<pre class="wp-block-code"><code>CREATE PROCEDURE UpdateInventoryQuantity
AS
BEGIN
    DECLARE @ProductID INT = 1

    
    WHILE @ProductID IS NOT NULL
    BEGIN
       
        UPDATE Products
        SET Quantity = Quantity + 10
        WHERE ID = @ProductID

        SELECT @ProductID = MIN(ID) FROM Products WHERE ID > @ProductID
    END
END
GO
</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" width="902" height="589" src="https://sqlserverguides.com/wp-content/uploads/2024/04/While-Loop-in-SQL-Server-Stored-Procedure.jpg" alt="While Loop in SQL Server Stored Procedure" class="wp-image-21075" style="width:629px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/04/While-Loop-in-SQL-Server-Stored-Procedure.jpg 902w, https://sqlserverguides.com/wp-content/uploads/2024/04/While-Loop-in-SQL-Server-Stored-Procedure-300x196.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2024/04/While-Loop-in-SQL-Server-Stored-Procedure-768x501.jpg 768w" sizes="(max-width: 902px) 100vw, 902px" /></figure>
</div>


<p class="wp-block-paragraph">From the above output, you have successfully created the stored procedure containing the while loop to update the quantity of each product by 10 each time whenever you call this stored procedure.</p>



<p class="wp-block-paragraph">Let&#8217;s understand the code part with <strong>BEGIN&#8230;END</strong> section.</p>



<p class="wp-block-paragraph">This line <strong>DECLARE @ProductID INT = 1</strong> creates a new variable named ProductID of type integer and initializes it with value 1.</p>



<p class="wp-block-paragraph">Then, <strong>WHILE LOOP</strong> begins with boolean conditions <strong>@ProductID IS NOT NULL</strong>. This means the loop runs as long as <strong>ProductID is not equal to NULL</strong>. Meanwhile, it does the following things.</p>



<ul class="wp-block-list">
<li>It begins the update on the Products table using the <strong>&#8216;UPDATE Products&#8217;</strong> statement and adds the 10 quantity to the value of the column <strong>&#8216;Quantity&#8217;</strong> using the statement <strong>&#8216;SET Quantity = Quantity + 10&#8217;</strong>.</li>



<li>It increases the quantity of the product where <strong>ID</strong> is equal to <strong>ProductID</strong> using the statement <strong>&#8216;WHERE ID = @ProductID&#8217;</strong>.</li>
</ul>



<p class="wp-block-paragraph">Then, the next line of code, <strong>&#8216;SELECT @ProductID = MIN(ID) FROM Products WHERE ID > @ProductID&#8217;</strong>, fetches the next ID of the product from the table and assigns this ID to the variable @ProductID.</p>



<p class="wp-block-paragraph">But how does it fetch the ID of the next product? It does so by comparing the current ID with the next ID. If the next ID is greater than the current ID, it assigns it to the variable ProductID.</p>



<p class="wp-block-paragraph">This is how the while loop with the stored procedure is used to update the quantity of the product.</p>



<p class="wp-block-paragraph">To add the 10 quantities to each product, just call this procedure using the code below.</p>



<pre class="wp-block-code"><code>EXEC UpdateInventoryQuantity;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" width="445" height="252" src="https://sqlserverguides.com/wp-content/uploads/2024/04/Calling-While-Loop-in-SQL-Server-Stored-Procedure.jpg" alt="Calling While Loop in SQL Server Stored Procedure" class="wp-image-21079" style="width:388px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/04/Calling-While-Loop-in-SQL-Server-Stored-Procedure.jpg 445w, https://sqlserverguides.com/wp-content/uploads/2024/04/Calling-While-Loop-in-SQL-Server-Stored-Procedure-300x170.jpg 300w" sizes="(max-width: 445px) 100vw, 445px" /></figure>
</div>


<p class="wp-block-paragraph">Look at the output; when you call the store procedure <strong>UpdateInventoryQuantity</strong>, it shows the number of rows updated, as you can see in the output.</p>



<p class="wp-block-paragraph">Now, let&#8217;s check the Products table to see whether the quantity has increased by 10.</p>



<pre class="wp-block-code"><code>SELECT * FROM Products</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="383" height="318" src="https://sqlserverguides.com/wp-content/uploads/2024/04/Checking-Products-Table-After-Calling-While-Loop-in-SQL-Server-Stored-Procedure.jpg" alt="Checking Products Table After Calling While Loop in SQL Server Stored Procedure" class="wp-image-21082" srcset="https://sqlserverguides.com/wp-content/uploads/2024/04/Checking-Products-Table-After-Calling-While-Loop-in-SQL-Server-Stored-Procedure.jpg 383w, https://sqlserverguides.com/wp-content/uploads/2024/04/Checking-Products-Table-After-Calling-While-Loop-in-SQL-Server-Stored-Procedure-300x249.jpg 300w" sizes="(max-width: 383px) 100vw, 383px" /></figure>
</div>


<p class="wp-block-paragraph">From the output, you can see that each product quantity is increased by 10 if you compare it with the previous picture that is shown at the beginning of this tutorial while creating the table.</p>



<p class="wp-block-paragraph">Well, from the above example, I hope that you understand how to use the while loop in stored procedure to perform repetitive operations on the database or table.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this SQL Server tutorial, you learned about the <strong>while loop in the SQL Server store procedure. </strong>You covered the while loop and its syntax and also learned about the fundamental concept of a stored procedure.</p>



<p class="wp-block-paragraph">Then, you learned how to use the while loop within the stored procedure by updating the product quantity by 10.</p>



<p class="wp-block-paragraph">You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/for-loop-in-sql-server-stored-procedure/">For Loop in SQL Server Stored Procedure</a></li>



<li><a href="https://sqlserverguides.com/how-to-use-if-else-in-sql-server-stored-procedure/">How to use IF-ELSE in SQL Server Stored Procedure</a></li>



<li><a href="https://sqlserverguides.com/how-to-view-stored-procedures-in-sql-server/">How to View Stored Procedures in SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SQL Server Find String in String</title>
		<link>https://sqlserverguides.com/sql-server-find-string-in-string/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Fri, 19 Apr 2024 11:00:45 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[SQL Server Find String in String]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=21043</guid>

					<description><![CDATA[In this SQL Server tutorial, you will learn about SQL Server find string in a string. While analysing the data, I needed to find the specific existence of the strings within the data containing strings. Actually, I needed to find the specific pattern of strings, so for that, I used the CHARINDEX() function. Apart from ... <a title="SQL Server Find String in String" class="read-more" href="https://sqlserverguides.com/sql-server-find-string-in-string/" aria-label="Read more about SQL Server Find String in String">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this SQL Server tutorial, you will learn about <strong>SQL Server find string in a string</strong>.</p>



<p class="wp-block-paragraph">While analysing the data, I needed to find the specific existence of the strings within the data containing strings. Actually, I needed to find the specific pattern of strings, so for that, I used the <strong>CHARINDEX()</strong> function.</p>



<p class="wp-block-paragraph">Apart from the <strong>CHARINDEX()</strong> function, I have also explained more methods called <strong>PATINDEX()</strong> to find the string in the string, which is similar to the char index but provides more control over finding the string.</p>



<p class="wp-block-paragraph">Let&#8217;s start,</p>



<h2 class="wp-block-heading">SQL Server Find String in String</h2>



<p class="wp-block-paragraph">To find the string within a string, SQL Server has several functions such as <strong>CHARINDEX()</strong>, <strong>PATINDEX()</strong> and <strong>SUBSTRING()</strong>.</p>



<p class="wp-block-paragraph">Here, find string in string means find the substring in string, so you will learn how to find the specified substring in the given string. But you can also find a complete string in a string.</p>



<p class="wp-block-paragraph">I will explain each of the functions to show you how to find a string in a string.</p>



<h3 class="wp-block-heading">SQL Server Find String in String Using CHARINDEX</h3>



<p class="wp-block-paragraph">The <strong>CHARINDEX()</strong> function in SQL Server searches the specific part of a string within another string and returns the starting position of that specific string. Otherwise, it returns 0 if that specified string is not found.</p>



<p class="wp-block-paragraph">The syntax is given on how to use the CHARINDEX() function.</p>



<pre class="wp-block-code"><code>CHARINDEX(substringToFind, stringToSearch, startingLocationForSearching)</code></pre>



<p class="wp-block-paragraph">Where,</p>



<ul class="wp-block-list">
<li><strong>CHARINDEX():</strong> A whole function returns the substring’s starting position.</li>



<li><strong>substringToFind</strong>: It is the substring or character expression whose starting position you want to know.</li>



<li><strong>stringToSearch: </strong>This is the source string that contains the substring that you want to find.</li>



<li><strong>startingLocationForSearching:</strong> The starting position where the search will start for the substring. If you forget to specify this option, the search begins by default from the beginning of the string.</li>
</ul>



<p class="wp-block-paragraph">If you want to know more about CHARINDEX() function, visit this tutorial <a href="https://sqlserverguides.com/charindex-function-in-sql-server/">CHARINDEX Function in SQL Server</a>.</p>



<p class="wp-block-paragraph">Let&#8217;s take an example and see.</p>



<p class="wp-block-paragraph">First, create a table named Customers using the query below.</p>



<pre class="wp-block-code"><code>CREATE TABLE Customers (
    CustomerID INT,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Address NVARCHAR(255)
);</code></pre>



<p class="wp-block-paragraph">Insert the following records.</p>



<pre class="wp-block-code"><code>INSERT INTO Customers (CustomerID, FirstName, LastName, Address)
VALUES
(373275, 'Gabriel', 'Judy', '123 Main Boulevard'),
(377385, 'Joe', 'Isabella', '456 Oak St'),
(370795, 'Logan', 'Julia', '789 Pine Boulevard'),
(376977, 'Alan', 'Grace', '101 Maple Lane'),
(366868, 'Juan', 'Albert', '234 Elm Street'),
(376489, 'Willie', 'Elijah', '567 Birch Boulevard'),
(353230, 'Wayne', 'Randy', '890 Cedar Blvd'),
(351173, 'Amber', 'Denise', '321 Spruce Avenue'),
(348721, 'Danielle', 'Marilyn', '654 Ash Boulevard'),
(371731, 'Beverly', 'Gabriel', '987 Walnut Street');</code></pre>



<p class="wp-block-paragraph">Use the query below to view the Customers Table.</p>



<pre class="wp-block-code"><code>SELECT * FROM Customers;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="537" height="378" src="https://sqlserverguides.com/wp-content/uploads/2024/04/Create-Customers-Table-Before-SQL-Server-Find-String-in-String-Using-CHARINDEX.jpg" alt="Create Customers Table Before SQL Server Find String in String Using CHARINDEX" class="wp-image-21052" srcset="https://sqlserverguides.com/wp-content/uploads/2024/04/Create-Customers-Table-Before-SQL-Server-Find-String-in-String-Using-CHARINDEX.jpg 537w, https://sqlserverguides.com/wp-content/uploads/2024/04/Create-Customers-Table-Before-SQL-Server-Find-String-in-String-Using-CHARINDEX-300x211.jpg 300w" sizes="(max-width: 537px) 100vw, 537px" /></figure>
</div>


<p class="wp-block-paragraph">Look at the above output, the table contains three columns FirstName, LastName and Customers.</p>



<p class="wp-block-paragraph">Now, suppose you need to find customers whose addresses contain the word &#8216;Boulevard&#8217;; for that, you can use the <strong>CHARINDEX()</strong> method, as shown below.</p>



<pre class="wp-block-code"><code>SELECT FirstName, LastName, Address
FROM Customers
WHERE CHARINDEX('Boulevard', Address) &gt; 0;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="626" height="292" src="https://sqlserverguides.com/wp-content/uploads/2024/04/SQL-Server-Find-String-in-String-Using-CHARINDEX.jpg" alt="SQL Server Find String in String Using CHARINDEX" class="wp-image-21054" style="width:527px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/04/SQL-Server-Find-String-in-String-Using-CHARINDEX.jpg 626w, https://sqlserverguides.com/wp-content/uploads/2024/04/SQL-Server-Find-String-in-String-Using-CHARINDEX-300x140.jpg 300w" sizes="(max-width: 626px) 100vw, 626px" /></figure>
</div>


<p class="wp-block-paragraph">From the output, you can see there are 4 customers whose address contains the word <strong>&#8216;Boulevard&#8217;</strong>.</p>



<p class="wp-block-paragraph">Here in the query part, <strong>CHARINDEX(&#8216;Boulevard&#8217;, Address) &gt; 0</strong>; takes the word &#8216;Boulevard&#8217; that you want to find in the address (which is the string), and second, it takes that address (in which the specified string you want to find).</p>



<p class="wp-block-paragraph">Then it compares the return result from 0. As you know, CHARINDEX returns the starting position of the substring in the string if it is found; otherwise, it returns 0, so check if the returned result is > 0.</p>



<p class="wp-block-paragraph">From the output, you can see 4 customers whose addresses contain the word &#8216;Boulevard&#8217; because the CHARINDEX() function returns non-zero for this word, which is greater than 0, and the given word exists.</p>



<p class="wp-block-paragraph">So as a result, you get 4 customers with the address containing the word &#8216;Boulevard&#8217;</p>



<p class="wp-block-paragraph">This is how to use the CHARINDEX() function to find the string in a string.</p>



<h3 class="wp-block-heading">SQL Server Find String in String Using PATINDEX</h3>



<p class="wp-block-paragraph">The <strong>PATINDEX()</strong> function in SQL Server acts similarly to the CHARINDEX() function you learned in the above section, but it allows you to include pattern matching using wildcards.</p>



<p class="wp-block-paragraph">So you can specify the string pattern that you want to find in the other string.</p>



<p class="wp-block-paragraph">The syntax is given how to use the PATINDEX() method.</p>



<pre class="wp-block-code"><code>PATINDEX ( '%pattern%' , string_value )</code></pre>



<p class="wp-block-paragraph">Where,</p>



<ul class="wp-block-list">
<li><strong>PATINDEX():</strong> This is the function that returns the starting position of the pattern in the string.</li>



<li><strong>%pattern%:</strong> It is the character string or substring that you want to find in the string, and it should surrounded by %. Also, with the pattern, you can specify the wildcards as LIKE, such as:
<ul class="wp-block-list">
<li>Underscore (_) to match a single character.</li>



<li>Brackets [] to match any characters inside it.</li>



<li>[^] means do not match any character inside it.</li>



<li>% to match a string of any length.</li>
</ul>
</li>



<li><strong>string_value:</strong> This is the source string where the starting position of the substring is found.</li>
</ul>



<p class="wp-block-paragraph">If you want to learn more about the PATINDEX() function, visit this tutorial <a href="https://sqlserverguides.com/patindex-function-in-sql-server/">PATINDEX Function in SQL Server</a>.</p>



<p class="wp-block-paragraph">Let&#8217;s take an example and understand how to use the PATINDEX() method to find a string in a string.</p>



<p class="wp-block-paragraph">Take the same Customer table that you have created in the above section. And suppose you need to find the customers whose address contains the string or word <strong>&#8216;street&#8217;.</strong> For that, you can use the <strong>PATINDEX() </strong>here as shown below.</p>



<pre class="wp-block-code"><code>SELECT FirstName, LastName, Address
FROM Customers
WHERE PATINDEX('%Street', Address) &gt; 0;</code></pre>



<p class="wp-block-paragraph">From the output, you can see that only two customers&#8217; addresses contain the string &#8216;Street&#8217;.</p>



<p class="wp-block-paragraph">Here, the query part <strong>PATINDEX(&#8216;%Street&#8217;, Address) &gt; 0;</strong> first takes the pattern <strong>&#8216;%Street&#8217;</strong> that you want to find in the address, and second is the address (or string) where you want to find the given pattern (or substring).</p>



<p class="wp-block-paragraph">This is how to use the PATINDEX() function in SQL Server to find the string in the string.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this SQl Server tutorial, you learned about <strong>SQL Server find string in a string</strong> using the CHARINDEX() and PATINDEX() functions.</p>



<p class="wp-block-paragraph">Additionally, you learnt about the syntax of both functions.</p>



<p class="wp-block-paragraph">You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-server-convert-xml-to-string/">SQL Server Convert XML to String</a></li>



<li><a href="https://sqlserverguides.com/sql-server-check-if-column-exists/">SQL Server Check If Column Exists</a></li>



<li><a href="https://sqlserverguides.com/how-to-drop-table-if-exists-in-sql-server/">How to Drop Table If Exists in SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to use IF-ELSE in SQL Server Stored Procedure</title>
		<link>https://sqlserverguides.com/how-to-use-if-else-in-sql-server-stored-procedure/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Thu, 07 Mar 2024 12:34:31 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Creating IF-ELSE in SQL Server Stored Procedure]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=20835</guid>

					<description><![CDATA[I will explain how to use IF-ELSE in SQL server stored procedure in this SQL Server tutorial. First, I will introduce the syntax of the IF-ELSE in SQL Server. Then, with an example, you will learn how to use the if-else in the stored procedure. You will create a stored procedure containing the if-else statement ... <a title="How to use IF-ELSE in SQL Server Stored Procedure" class="read-more" href="https://sqlserverguides.com/how-to-use-if-else-in-sql-server-stored-procedure/" aria-label="Read more about How to use IF-ELSE in SQL Server Stored Procedure">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">I will explain<strong> how to use IF-ELSE in SQL server stored procedure in this SQL Server tutorial.</strong></p>



<p class="wp-block-paragraph">First, I will introduce the syntax of the <strong>IF-ELSE</strong> in SQL Server. Then, with an example, you will learn how to use the if-else in the stored procedure.</p>



<p class="wp-block-paragraph">You will create a stored procedure containing the if-else statement and execute the sql statement of the stored procedure based on the condition.</p>



<h2 class="wp-block-heading">IF-ELSE in SQL Server Stored Procedure</h2>



<p class="wp-block-paragraph">To know how to use IF-ELSE in an SQL Server stored procedure, first, you must understand the if-else statement in SQL Server. This statement is used for conditional logic.</p>



<p class="wp-block-paragraph">The syntax of the if-else is given below.</p>



<pre class="wp-block-code"><code>IF condition
	BEGIN
    	--  Write a SQL statemetn that is executed when condtion is true
	END
ELSE
	BEGIN
    	-- Write a SQL statemetn that is executed when condtion is false
	END
</code></pre>



<p class="wp-block-paragraph">Where,</p>



<ul class="wp-block-list">
<li><b>IF condition: </b>Here, IF is the keyword followed by the condition, which can be any expression that must evaluate to a true or false value (or boolean value).</li>



<li><strong>BEGIN and END:</strong> If the condition is true, then this section of IF is executed; otherwise, the ELSE section of the BEGIN&#8230;END block is executed. Remember, this section contains the SQL statement, query, or operation you want to execute based on the condition.</li>
</ul>



<p class="wp-block-paragraph">This is all about how you can use the if-else in the SQL Server, next let&#8217;s take an example where we will create stored procedure which contains the if-else statement.</p>



<p class="wp-block-paragraph">I have the <strong>SalesTransactions</strong> table in the database&#8217;s <strong>Sales</strong> scheme, shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="582" height="324" src="https://sqlserverguides.com/wp-content/uploads/2024/03/IF-ELSE-in-SQL-Server-Stored-Procedure-SalesTransactions-Table.jpg" alt="IF-ELSE in SQL Server Stored Procedure SalesTransactions Table" class="wp-image-20838" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/IF-ELSE-in-SQL-Server-Stored-Procedure-SalesTransactions-Table.jpg 582w, https://sqlserverguides.com/wp-content/uploads/2024/03/IF-ELSE-in-SQL-Server-Stored-Procedure-SalesTransactions-Table-300x167.jpg 300w" sizes="(max-width: 582px) 100vw, 582px" /></figure>
</div>


<p class="wp-block-paragraph">Look at the data of the SalesTransactions in the above picture, </p>



<p class="wp-block-paragraph">So here you have to create a stored procedure that takes the <strong>TransactionID </strong>as input, checks if the <strong>SaleAmount</strong> for the give transaction is greater than <strong>$100</strong>, if it is, the procedure computes the total amount including tax.</p>



<p class="wp-block-paragraph">If the transaction is not greater than <strong>$100</strong>, it simply returns the <strong>SaleAmount</strong> without tax.</p>



<p class="wp-block-paragraph">For that, you can look at the stored procedure ComputeTotalAmount.</p>



<pre class="wp-block-code"><code>CREATE PROCEDURE CalculateTotalAmount
	@TransactionID INT
AS
BEGIN
	DECLARE @SaleAmount DECIMAL(10, 2);
	DECLARE @TaxRate DECIMAL(5, 2);
	DECLARE @TotalAmount DECIMAL(10, 2);

	SELECT @SaleAmount = SaleAmount, @TaxRate = TaxRate
	FROM Sales.SalesTransactions
	WHERE TransactionID = @TransactionID

	IF @SaleAmount &gt; 100
	BEGIN
    	SET @TotalAmount = @SaleAmount + (@SaleAmount * @TaxRate)
    	PRINT 'Total Amount including tax: ' + CAST(@TotalAmount AS VARCHAR)
	END
	ELSE
	BEGIN
    	PRINT 'Total Amount (no tax applied): ' + CAST(@SaleAmount AS VARCHAR)
	END
END</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="723" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Creating-IF-ELSE-in-SQL-Server-Stored-Procedure-1024x723.jpg" alt="Creating IF-ELSE in SQL Server Stored Procedure" class="wp-image-20840" style="width:697px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Creating-IF-ELSE-in-SQL-Server-Stored-Procedure-1024x723.jpg 1024w, https://sqlserverguides.com/wp-content/uploads/2024/03/Creating-IF-ELSE-in-SQL-Server-Stored-Procedure-300x212.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2024/03/Creating-IF-ELSE-in-SQL-Server-Stored-Procedure-768x542.jpg 768w, https://sqlserverguides.com/wp-content/uploads/2024/03/Creating-IF-ELSE-in-SQL-Server-Stored-Procedure.jpg 1064w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">In the above-stored procedure, accept the <strong>TransactionID</strong> of tye <strong>INT</strong> as input and declare the three variables <strong>@SaleAmount</strong>, <strong>@TaxRate</strong> and <strong>@TotalAmount</strong> of type Decimal.</p>



<p class="wp-block-paragraph">After that, a statement <strong>SELECT @SaleAmount = SaleAmount, @TaxRate = TaxRate FROM Sales.SalesTransactions WHERE TransactionID = @TransactionID</strong> retrieves the SaleAmount and TaxRat for the given TransactionID from the Sales.SalesTransactions table.</p>



<p class="wp-block-paragraph">Then, the IF-ELSE checks <strong>if the SaleAmount is greater than $100. If true, it computes the total amount, including tax, and prints it</strong>. Otherwise, it prints the sale amount without adding tax in case of falsity.</p>



<p class="wp-block-paragraph">Let&#8217;s check the stored procedure with <strong>TransactionID</strong>. For example, input the <strong>TransactionID as 1 to CalculateTotalAmount</strong>, as shown below.</p>



<pre class="wp-block-code"><code>EXEC CalculateTotalAmount 1;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="435" height="150" src="https://sqlserverguides.com/wp-content/uploads/2024/03/IF-ELSE-in-SQL-Server-Stored-Procedure.jpg" alt="IF-ELSE in SQL Server Stored Procedure" class="wp-image-20843" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/IF-ELSE-in-SQL-Server-Stored-Procedure.jpg 435w, https://sqlserverguides.com/wp-content/uploads/2024/03/IF-ELSE-in-SQL-Server-Stored-Procedure-300x103.jpg 300w" sizes="(max-width: 435px) 100vw, 435px" /></figure>
</div>


<p class="wp-block-paragraph">Look at the output. When you pass the TransactionID as 1, the procedure returns the total amount as 100 without tax applied to it. That is because the IF condition becomes false in the Stored procedure, and it simply executes the ESLE block.</p>



<p class="wp-block-paragraph">Now, let&#8217;s pass the different transaction IDs.</p>



<pre class="wp-block-code"><code>EXEC CalculateTotalAmount 2;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="466" height="149" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Testing-IF-ELSE-in-SQL-Server-Stored-Procedure.jpg" alt="Testing IF-ELSE in SQL Server Stored Procedure" class="wp-image-20846" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Testing-IF-ELSE-in-SQL-Server-Stored-Procedure.jpg 466w, https://sqlserverguides.com/wp-content/uploads/2024/03/Testing-IF-ELSE-in-SQL-Server-Stored-Procedure-300x96.jpg 300w" sizes="(max-width: 466px) 100vw, 466px" /></figure>
</div>


<p class="wp-block-paragraph">This time, when you pass the transaction as 2 it returns the total amount including the tax here IF condition becomes true because if you check the sale amount of given transaction ID in the database, <strong>which is $200</strong>.</p>



<p class="wp-block-paragraph">The above is a simple example of an if-else statement in a stored procedure; you can even nest the if-else statement in the stored procedure.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this SQL Server tutorial, you learned how to use IF-ELSE in SQL server stored procedure in this SQL Server tutorial.</p>



<p class="wp-block-paragraph">Also learned the syntax of IF-ELSE statement, For example you created the CalculateTotalAmount stored procedure based on the provided TransactionID it executes the if-else block with procedure.</p>



<p class="wp-block-paragraph">You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/how-to-delete-stored-procedures-in-sql-server/">How to Delete Stored Procedures in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/for-loop-in-sql-server-stored-procedure/">For Loop in SQL Server Stored Procedure</a></li>



<li><a href="https://sqlserverguides.com/create-temp-table-in-sql-server-stored-procedure/">Create Temp Table in SQL Server Stored Procedure</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Delete Stored Procedures in SQL Server</title>
		<link>https://sqlserverguides.com/how-to-delete-stored-procedures-in-sql-server/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Thu, 07 Mar 2024 12:27:37 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Delete Stored Procedures in SQL Server]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=20813</guid>

					<description><![CDATA[As a database developer, you must know how to delete stored procedures in SQL Server when they are no longer needed. In this SQL Server tutorial, I will explain two methods for removing stored procedures from the database. In the first method, you will use the SSMS to delete the stored procedures; in the second, ... <a title="How to Delete Stored Procedures in SQL Server" class="read-more" href="https://sqlserverguides.com/how-to-delete-stored-procedures-in-sql-server/" aria-label="Read more about How to Delete Stored Procedures in SQL Server">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><strong>As a database developer, you must know how to delete stored procedures in SQL Server when they are no longer needed.</strong></p>



<p class="wp-block-paragraph">In this SQL Server tutorial, I will explain two methods for removing stored procedures from the database.</p>



<p class="wp-block-paragraph">In the first method, you will use the SSMS to delete the stored procedures; in the second, you will use the query.</p>



<p class="wp-block-paragraph">Let&#8217;s start,</p>



<h2 class="wp-block-heading">Delete Stored Procedures in SQL Server</h2>



<p class="wp-block-paragraph"><strong>The command DELETE PROCEDURE can be used to delete stored procedures in SQL Server. You can also use the SQL Server Management Studio (SSMS) to remove the stored procedure in your database.</strong></p>



<p class="wp-block-paragraph">But <strong>why remove the stored procedure?</strong> Due to changes in the business logic, when you don&#8217;t need the stored procedure or replace it with new logic, you remove the stored procedure.</p>



<p class="wp-block-paragraph">Let&#8217;s start,</p>



<h2 class="wp-block-heading">Delete Stored Procedures in the SQL Server using SSMS</h2>



<p class="wp-block-paragraph">You delete stored procedures in SQL Server using the SQL Server Management Studio, a graphical user interface for managing SQL Server Database. </p>



<p class="wp-block-paragraph">First, let me show you how to view all the stored procedures in your current database.</p>



<p class="wp-block-paragraph">Open the <strong>SSMS</strong>, go to the left side of the <strong>Object Explorer</strong>, expand the <strong>Database</strong> folder, choose the database that contains the stored procedure, expand the <strong>Programmability</strong> subfolder, and finally expand the <strong>Stored Procedures</strong> subfolder, as shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="486" height="519" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Viewing-Procedures-Before-to-Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS.jpg" alt="Viewing Procedures Before to  Delete Stored Procedures in the SQL Server using SSMS" class="wp-image-20816" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Viewing-Procedures-Before-to-Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS.jpg 486w, https://sqlserverguides.com/wp-content/uploads/2024/03/Viewing-Procedures-Before-to-Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS-281x300.jpg 281w" sizes="(max-width: 486px) 100vw, 486px" /></figure>
</div>


<p class="wp-block-paragraph">The subfolder Stored Procedures contains all the system—and user-created stored procedures; for example, store procedure <strong>dbo.uspCounter</strong>.</p>



<p class="wp-block-paragraph">To delete this stored procedure, <strong>select and right-click on it</strong>, then select the <strong>Delete</strong> option, as shown in the below picture.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="529" height="591" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Selecting-Delete-Option-to-Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS.png" alt="Selecting Delete Option to Delete Stored Procedures in the SQL Server using SSMS" class="wp-image-20819" style="width:366px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Selecting-Delete-Option-to-Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS.png 529w, https://sqlserverguides.com/wp-content/uploads/2024/03/Selecting-Delete-Option-to-Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS-269x300.png 269w" sizes="(max-width: 529px) 100vw, 529px" /></figure>
</div>


<p class="wp-block-paragraph">When you click the <strong>Delete</strong> option, it opens the Delete Object dialogue below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="930" height="812" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS.jpg" alt="Delete Stored Procedures in the SQL Server using SSMS" class="wp-image-20821" style="width:563px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS.jpg 930w, https://sqlserverguides.com/wp-content/uploads/2024/03/Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS-300x262.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2024/03/Delete-Stored-Procedures-in-the-SQL-Server-using-SSMS-768x671.jpg 768w" sizes="(max-width: 930px) 100vw, 930px" /></figure>
</div>


<p class="wp-block-paragraph">To completely delete it, click the <strong>OK</strong> button at the bottom right of the dialogue box, as shown in the above output.</p>



<p class="wp-block-paragraph">When you reopen the Stored Procedures subfolder, you won&#8217;t see the deleted stored procedure. In the picture below, the <strong>dbo.uspCounter</strong> is removed.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="381" height="254" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Viewing-Deleted-Stored-Procedures-in-the-SQL-Server-using-SSMS.jpg" alt="Viewing Deleted Stored Procedures in the SQL Server using SSMS" class="wp-image-20826" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Viewing-Deleted-Stored-Procedures-in-the-SQL-Server-using-SSMS.jpg 381w, https://sqlserverguides.com/wp-content/uploads/2024/03/Viewing-Deleted-Stored-Procedures-in-the-SQL-Server-using-SSMS-300x200.jpg 300w" sizes="(max-width: 381px) 100vw, 381px" /></figure>
</div>


<p class="wp-block-paragraph">You don&#8217;t see any stored procedures with the name <strong>&#8216;dbo.uspCounter&#8217;</strong> in the list because you deleted it.</p>



<p class="wp-block-paragraph">This is how to Delete Stored Procedures in the SQL Server using SSMS.</p>



<h2 class="wp-block-heading">Delete Stored Procedures in the SQL Server using Query</h2>



<p class="wp-block-paragraph">You just learned how to delete the stored procedure using the SSMS; here, you will learn how to remove the stored procedure using the command <strong>DROP PROCEDURE</strong> in SQL Server.</p>



<p class="wp-block-paragraph">The syntax is given below.</p>



<pre class="wp-block-code"><code>DROP PROCEDURE name_of_procedure;</code></pre>



<p class="wp-block-paragraph">Where,</p>



<ul class="wp-block-list">
<li><strong>DROP PROCEDURE: </strong>It is the command to delete the specified stored procedure.</li>



<li><strong>name_of_procedure:</strong> This represents the name of the stored procedure that you want to delete from the database.</li>
</ul>



<p class="wp-block-paragraph">First, execute the query below to list all the procedures stored in the current database.</p>



<pre class="wp-block-code"><code>SELECT name AS procedure_name
    , SCHEMA_NAME(schema_id) AS schema_name
    , type_desc
    , create_date
    , modify_date
FROM sys.procedures;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="819" height="448" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Listing-Stored-Procedure-using-the-Query-to-Delete.jpg" alt="Listing Stored Procedure using the Query to Delete" class="wp-image-20827" style="width:706px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Listing-Stored-Procedure-using-the-Query-to-Delete.jpg 819w, https://sqlserverguides.com/wp-content/uploads/2024/03/Listing-Stored-Procedure-using-the-Query-to-Delete-300x164.jpg 300w, https://sqlserverguides.com/wp-content/uploads/2024/03/Listing-Stored-Procedure-using-the-Query-to-Delete-768x420.jpg 768w" sizes="(max-width: 819px) 100vw, 819px" /></figure>
</div>


<p class="wp-block-paragraph">Let&#8217;s say you must delete the <strong>usp_GetEmployees</strong> stored procedure from the listed stored procedure. For that, you can use the <strong>DROP PROCEDURE</strong> command, as shown below.</p>



<pre class="wp-block-code"><code>DROP PROCEDURE usp_GetEmployees;</code></pre>



<p class="wp-block-paragraph">When you execute the above query, the specified stored procedure is deleted. So again, execute the below query to view all the procedures stored in the current database.</p>



<pre class="wp-block-code"><code>SELECT name AS procedure_name FROM sys.procedures;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="712" height="290" src="https://sqlserverguides.com/wp-content/uploads/2024/03/Delete-Stored-Procedures-in-the-SQL-Server-using-Query.jpg" alt="Delete Stored Procedures in the SQL Server using Query" class="wp-image-20829" srcset="https://sqlserverguides.com/wp-content/uploads/2024/03/Delete-Stored-Procedures-in-the-SQL-Server-using-Query.jpg 712w, https://sqlserverguides.com/wp-content/uploads/2024/03/Delete-Stored-Procedures-in-the-SQL-Server-using-Query-300x122.jpg 300w" sizes="(max-width: 712px) 100vw, 712px" /></figure>
</div>


<p class="wp-block-paragraph">From the output, you can see the stored procedure <strong>usp_GetEmployees</strong> doesn&#8217;t exist anymore cause it is deleted.</p>



<p class="wp-block-paragraph">This is how to delete stored procedures in SQL Server using the query.</p>



<ul class="wp-block-list">
<li>Some practices that you must know before deleting any stored procedure.</li>



<li>Always have a backup of the stored procedures before deletion.</li>



<li>Ensure that the stored procedure you delete does not rely on other database objects, like triggers or other stored procedures.</li>



<li>Use the transaction while deleting the stored procedures to prevent any partial changes in case any error occurs.</li>



<li>Always keep track of the stored procedure you deleted and why you deleted it for future reference.</li>
</ul>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this SQL Server tutorial, you learned how to delete stored procedures in SQL Server using the SSMS and query.</p>



<p class="wp-block-paragraph">You learned step-by-step processes for removing stored procedures using SQL Server Management. Then, you used the DROP PROCEDURE command as a query to delete the stored procedure.</p>



<p class="wp-block-paragraph"> You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/sql-server-call-stored-procedure-from-another-stored-procedure/">SQL Server Call Stored Procedure from another Stored Procedure</a></li>



<li><a href="https://sqlserverguides.com/how-to-test-stored-procedures-in-sql-server/">How to Test Stored Procedures in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/rename-stored-procedure-in-sql-server/">Rename Stored Procedure in SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>For Loop in SQL Server Stored Procedure</title>
		<link>https://sqlserverguides.com/for-loop-in-sql-server-stored-procedure/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Thu, 07 Mar 2024 12:19:22 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[FOR loop in SQL Server Stored Procedure]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=20774</guid>

					<description><![CDATA[In this SQL Server tutorial, you will understand the FOR loop in SQL Server stored procedure and learn how to use it. As a database developer, if you are familiar with SQL Server, then you already know that SQL Server doesn&#8217;t have a FOR loop. So, I will explain how you can simulate the FOR ... <a title="For Loop in SQL Server Stored Procedure" class="read-more" href="https://sqlserverguides.com/for-loop-in-sql-server-stored-procedure/" aria-label="Read more about For Loop in SQL Server Stored Procedure">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this SQL Server tutorial, <strong>you will understand the FOR loop in SQL Server stored procedure and learn how to use it.</strong></p>



<p class="wp-block-paragraph">As a database developer, if you are familiar with SQL Server, then you already know that SQL Server doesn&#8217;t have a <strong>FOR</strong> loop.</p>



<p class="wp-block-paragraph">So, I will explain how you can simulate the FOR loop in the SQL Server stored procedure.</p>



<h2 class="wp-block-heading">For Loop in SQL Server Stored Procedure</h2>



<p class="wp-block-paragraph">First, I want to say that SQL Server doesn&#8217;t have <strong>&#8216;FOR LOOP&#8217;</strong>, but you can achieve similar iterative processing using the &#8216;WHILE&#8217; loop.</p>



<p class="wp-block-paragraph">So, instead of &#8216;FOR LOOP&#8217;, you will use the &#8216;WHILE&#8217; loop in the SQL Server stored procedure.</p>



<p class="wp-block-paragraph">Let&#8217;s see the syntax of the WHILE loop, which is structured to repeatedly execute a block of statements as long as a specified condition is true.</p>



<pre class="wp-block-code"><code>WHILE &#91;condition]
BEGIN
	-- SQL statements to execute
END
</code></pre>



<p class="wp-block-paragraph">Where, </p>



<ul class="wp-block-list">
<li><strong>WHILE:</strong> This is the beginning of the loop, and the loop continues as long as the condition specified next to &#8216;WHILE&#8217; evaluates to &#8216;True&#8217;.</li>



<li><strong>condition:</strong> This is the boolean expression. If it is true, then the statement or logic within the loop is executed. If it becomes false, the loop ends, and control is passed to the next statement following the &#8216;END&#8217; keyword.</li>



<li><strong>BEGIN&#8230;END: </strong>This is where all the statements that must be executed repeatedly are kept.</li>
</ul>



<p class="wp-block-paragraph">Let&#8217;s take an example of how to use the WHILE loop. </p>



<pre class="wp-block-code"><code>DECLARE @Count INT = 1;

WHILE @Count &lt;= 5 
BEGIN
	PRINT 'Count is: ' + CAST(@Count AS VARCHAR); 
	SET @Count = @Count + 1; 
END</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="773" height="497" src="https://sqlserverguides.com/wp-content/uploads/2024/02/WHILE-loop-in-SQL-Server-Stored-Procedure.png" alt="WHILE loop in SQL Server Stored Procedure" class="wp-image-20778" style="width:614px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/WHILE-loop-in-SQL-Server-Stored-Procedure.png 773w, https://sqlserverguides.com/wp-content/uploads/2024/02/WHILE-loop-in-SQL-Server-Stored-Procedure-300x193.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/WHILE-loop-in-SQL-Server-Stored-Procedure-768x494.png 768w" sizes="(max-width: 773px) 100vw, 773px" /></figure>
</div>


<p class="wp-block-paragraph">From the above output, you can see that the<strong> &#8216;WHILE&#8217;</strong> loop prints the value of <strong>&#8216;@count&#8217;</strong> and increments it by <strong>1</strong> in each iteration. The loop continues if <strong>&#8216;@Count&#8217;</strong> is less than or equal to <strong>5</strong>.</p>



<p class="wp-block-paragraph">Let me explain what happens in detail; first, initialize the <strong>@Count</strong> variable of type INT with value 1.</p>



<p class="wp-block-paragraph">Then, WHILE loop begins with condition <strong>@Count &lt; 5</strong>, which means the loop runs as long as the value @count variable is less than 5.</p>



<p class="wp-block-paragraph">Then, within the BEGIN and END block, the first statement <strong>PRINT &#8216;Count is: &#8216; + CAST(@Count AS VARCHAR)</strong> prints the current value of counter variable @Count. After that, the next statement, <strong>SET @Count = @Count + 1</strong>, increases the current value of @Count by 1 at each iteration.</p>



<p class="wp-block-paragraph">In each iteration, it prints the incremented value of the @Count variable that you can see in the output.</p>



<p class="wp-block-paragraph">Now that you know how the <strong>WHILE loop works</strong>, it&#8217;s time to learn how to use it in the SQL Server stored procedure.</p>



<p class="wp-block-paragraph">Before proceeding, if you don&#8217;t know how to create a stored procedure, then visit this tutorial <a href="https://sqlserverguides.com/create-stored-procedure-in-sql-server/">Create Stored Procedure in SQL Server</a></p>



<p class="wp-block-paragraph">Use the below command to create the <strong>uspCounter </strong>stored procedure, which prints the counter&#8217;s value five times, as shown below.</p>



<pre class="wp-block-code"><code>CREATE PROCEDURE uspCounter
AS
BEGIN
	DECLARE @Count INT = 1;

	WHILE @Count &lt;= 5 
	BEGIN
		PRINT 'Count is: ' + CAST(@Count AS VARCHAR); 
		SET @Count = @Count + 1; 
	END;
END;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="810" height="627" src="https://sqlserverguides.com/wp-content/uploads/2024/02/FOR-loop-in-SQL-Server-Stored-Procedure.png" alt="FOR loop in SQL Server Stored Procedure" class="wp-image-20781" style="width:583px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/FOR-loop-in-SQL-Server-Stored-Procedure.png 810w, https://sqlserverguides.com/wp-content/uploads/2024/02/FOR-loop-in-SQL-Server-Stored-Procedure-300x232.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/FOR-loop-in-SQL-Server-Stored-Procedure-768x594.png 768w" sizes="(max-width: 810px) 100vw, 810px" /></figure>
</div>


<p class="wp-block-paragraph">The <strong>&#8216;WHILE&#8217;</strong> loop is used in the stored procedure <strong>uspCounter</strong>; this is the same one you learned. All you have to do is to place the while loop within the <strong>BEGIN and END</strong> blocks of the stored procedure.</p>



<p class="wp-block-paragraph">This is how to use the WHILE loop in a stored procedure; as the FOR loop is not supported, you can use the WHILE loop to achieve the same task and functionality.</p>



<p class="wp-block-paragraph">In the stored procedure, you can insert the records using the WHILE loop.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this SQL Server tutorial, you learned how to use the FOR loop in the SQL Server stored procedure; in reality, you have used the WHILE loop instead of the FOR loop, which behaves similarly to the FOR loop.</p>



<p class="wp-block-paragraph">You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/create-temp-table-in-sql-server-stored-procedure/">Create Temp Table in SQL Server Stored Procedure</a></li>



<li><a href="https://sqlserverguides.com/how-to-view-stored-procedures-in-sql-server/">How to View Stored Procedures in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/how-to-alter-stored-procedure-in-sql-server/">How to Alter Stored Procedure in SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Create Temp Table in SQL Server Stored Procedure</title>
		<link>https://sqlserverguides.com/create-temp-table-in-sql-server-stored-procedure/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Thu, 07 Mar 2024 12:12:47 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Create Temp Table in SQL Server Stored Procedure]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=20795</guid>

					<description><![CDATA[In this SQL Server tutorial, I will show you how to create temp table in SQL Server stored procedure. First, I will explain a temp table and its use in stored procedures. Then, with the example, you will understand how to use the CREATE TABLE command in the stored procedure to create a temp table. ... <a title="Create Temp Table in SQL Server Stored Procedure" class="read-more" href="https://sqlserverguides.com/create-temp-table-in-sql-server-stored-procedure/" aria-label="Read more about Create Temp Table in SQL Server Stored Procedure">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this SQL Server tutorial, <strong>I will show you how to create temp table in SQL Server stored procedure.</strong></p>



<p class="wp-block-paragraph">First, I will explain a temp table and its use in stored procedures. Then, with the example, you will understand how to use the <strong>CREATE TABLE</strong> command in the stored procedure to create a temp table.</p>



<p class="wp-block-paragraph">Also, how to insert the data into the temp table, and finally, how to use the temp table in stored procedure to perform some operations.</p>



<h2 class="wp-block-heading">Create Temp Table in SQL Server Stored Procedure</h2>



<p class="wp-block-paragraph">First, you must know what a temporary (temp) table in SQL Server is. <strong>The temp table is created at runtime to temporarily store the intermediate data while executing a SQL Script or stored procedure.</strong></p>



<p class="wp-block-paragraph">These tables don&#8217;t exist physically and are automatically deleted when the session ends. The user can also explicitly delete them. There are two kinds of temporary tables: local and global temp tables.</p>



<p class="wp-block-paragraph"><strong>The local temp table is denoted by a single has symbol (#) and visible to the connection that creates them, and the global temp table is denoted by a double has symbol (##) and visible to all the connection</strong></p>



<p class="wp-block-paragraph">If you don&#8217;t know how to create a temporary table, follow this tutorial <a href="https://sqlserverguides.com/create-temporary-table-in-sql-server-management-studio/">How to Create Temporary Table in SQL Server Management Studio?</a></p>



<p class="wp-block-paragraph">But the question is, why use the temporary table in the stored procedure? There are several reasons: performance, organization, scope and cleanup, and debugging.</p>



<p class="wp-block-paragraph">Now that you know about the temporary table and why you should use it in a stored procedure, let&#8217;s see how to create a temp table using the stored procedure.</p>



<p class="wp-block-paragraph">I have a table of <strong>SalesTransactions </strong>in my database, shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="680" height="352" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure-Table-Tansactions.png" alt="Create Temp Table in SQL Server Stored Procedure Table Tansactions" class="wp-image-20803" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure-Table-Tansactions.png 680w, https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure-Table-Tansactions-300x155.png 300w" sizes="(max-width: 680px) 100vw, 680px" /></figure>
</div>


<p class="wp-block-paragraph">Using this table, you have to create a stored procedure <strong>CalculateTotalSaleIncludingTax</strong>. The task of this stored procedure is to take all the data of the <strong>SalesTransactions</strong> table and store it in the new table <strong>#SaleData</strong>, then compute the total sale amount, including the tax for each transaction.</p>



<p class="wp-block-paragraph">Now look at the query below, which does the same task.</p>



<pre class="wp-block-code"><code>CREATE PROCEDURE CalculateTotalSaleIncludingTax
AS
BEGIN
    -- Create a temporary table to store sale data
    CREATE TABLE #SaleData (
        TransactionID INT,
        SaleAmount MONEY,
        TaxRate DECIMAL(5, 2)
    );

    -- Insert data into the temporary table
    INSERT INTO #SaleData (TransactionID, SaleAmount, TaxRate) 
	SELECT TransactionID, SaleAmount, TaxRate FROM Sales.SalesTransactions;

    -- Calculate total sale amount including tax for each transaction
    SELECT 
        TransactionID, 
        SaleAmount, 
        TaxRate, 
        SaleAmount + (SaleAmount * (TaxRate / 100.0)) AS TotalSaleIncludingTax
    FROM #SaleData
    ORDER BY TransactionID;
END
</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="679" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure-1024x679.png" alt="Create Temp Table in SQL Server Stored Procedure" class="wp-image-20801" style="width:620px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure-1024x679.png 1024w, https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure-300x199.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure-768x509.png 768w, https://sqlserverguides.com/wp-content/uploads/2024/02/Create-Temp-Table-in-SQL-Server-Stored-Procedure.png 1068w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">After executing the above command, a stored procedure, <strong>CalculateTotalSaleIncludingTax</strong>, is created. This procedure computes each transaction&#8217;s total sale amount, including tax.</p>



<p class="wp-block-paragraph">Let us understand each statement with stored procedure.</p>



<pre class="wp-block-code"><code>CREATE TABLE #SaleData (
        TransactionID INT,
        SaleAmount MONEY,
        TaxRate DECIMAL(5, 2)
    );</code></pre>



<p class="wp-block-paragraph">This command creates a temp table named <strong>#SaleData</strong> with columns <strong>TansactionID</strong>, <strong>SaleAmount</strong> and <strong>TaxRate</strong>. This is where you must focus on defining the temp table in the stored procedure.</p>



<p class="wp-block-paragraph">Next statement,</p>



<pre class="wp-block-code"><code>INSERT INTO #SaleData (TransactionID, SaleAmount, TaxRate) 
	SELECT TransactionID, SaleAmount, TaxRate FROM Sales.SalesTransactions;</code></pre>



<p class="wp-block-paragraph">This statement takes all the records from the SalesTransactions table and inserts them into temp table <strong>#SaleData</strong>.</p>



<p class="wp-block-paragraph">The final statement,</p>



<pre class="wp-block-code"><code>SELECT 
        TransactionID, 
        SaleAmount, 
        TaxRate, 
        SaleAmount + (SaleAmount * (TaxRate / 100.0)) AS TotalSaleIncludingTax
    FROM #SaleData
    ORDER BY TransactionID;</code></pre>



<p class="wp-block-paragraph">This statement computes the total sale, including the tax for each transaction record. Here, the select command is called on the temp table <strong>#SaleData</strong>.</p>



<p class="wp-block-paragraph">Now you know how the <strong>CalculateTotalSaleIncludingTax</strong> stored procedure works, execute this stored procedure.</p>



<pre class="wp-block-code"><code>EXEC CalculateTotalSaleIncludingTax;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="559" height="374" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-to-Create-Temp-Table.png" alt="Executing Stored Procedure to Create Temp Table" class="wp-image-20807" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-to-Create-Temp-Table.png 559w, https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-to-Create-Temp-Table-300x201.png 300w" sizes="(max-width: 559px) 100vw, 559px" /></figure>
</div>


<p class="wp-block-paragraph">The stored procedure returns the total sale amount, including the tax for each transaction ID.</p>



<p class="wp-block-paragraph">Here, you have to focus on the part where the temporary table is created, data is inserted into that table with a stored procedure, and how to use the temporary table to perform some operations.</p>



<p class="wp-block-paragraph">This is how you can create temp table in SQL Server stored procedure.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this SQL Server tutorial, you learned how to create temp table in SQL Servers stored procedure.</p>



<p class="wp-block-paragraph">Additionally, you learned how to perform some operations on the temp table using a stored procedure and retrieve the required information, such as total sales, including tax.</p>



<p class="wp-block-paragraph">You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/how-to-create-index-on-temp-table-in-sql-server/" target="_blank" rel="noreferrer noopener">How to Create Index on Temp Table in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/sql-server-insert-into-temp-table/" target="_blank" rel="noreferrer noopener">SQL Server Insert Into Temp Table</a></li>



<li><a href="https://sqlserverguides.com/create-sql-server-stored-procedure-default-parameter/">Create SQL Server Stored Procedure Default Parameter</a></li>



<li><a href="https://sqlserverguides.com/how-to-alter-stored-procedure-in-sql-server/">How to Alter Stored Procedure in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/how-to-view-stored-procedures-in-sql-server/">How to View Stored Procedures in SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to View Stored Procedures in SQL Server</title>
		<link>https://sqlserverguides.com/how-to-view-stored-procedures-in-sql-server/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Mon, 04 Mar 2024 13:50:21 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[View Stored Procedures in SQL Server]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=20692</guid>

					<description><![CDATA[In this SQL Server tutorial, you will understand how to view stored procedures in SQL Server. As a database developer, you must know how to view a stored procedure, which is helpful in many ways, such as debugging, optimizing, and understanding database schema. So, here I will explain how to view stored procedures using SSMS ... <a title="How to View Stored Procedures in SQL Server" class="read-more" href="https://sqlserverguides.com/how-to-view-stored-procedures-in-sql-server/" aria-label="Read more about How to View Stored Procedures in SQL Server">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this SQL Server tutorial, <strong>you will understand how to view stored procedures in SQL Server.</strong></p>



<p class="wp-block-paragraph">As a database developer, you must know how to view a stored procedure, which is helpful in many ways, such as debugging, optimizing, and understanding database schema.</p>



<p class="wp-block-paragraph">So, here I will explain how to view stored procedures using SSMS and Query. You will learn how to view all the stored procedures in a specific database and also how to view the definition of stored procedures.</p>



<p class="wp-block-paragraph">Let&#8217;s start,</p>



<h2 class="wp-block-heading">How to View Stored Procedures in SQL Server</h2>



<p class="wp-block-paragraph"><strong>There are multiple ways to view stored procedures in SQL Server, and here I will show each way.</strong></p>



<p class="wp-block-paragraph">First is using the SQL Server Management Studio (SSMS); if you use the SSMS, you can easily view all the stored procedures in a specific database.</p>



<p class="wp-block-paragraph">Open the SSMS and connect the SQL Server instance, and then you will see the window interface as shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="563" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Databases-Which-Contains-the-Stored-Procedure-1024x563.png" alt="Viewing Location of Databases Which Contains the Stored Procedure" class="wp-image-20693" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Databases-Which-Contains-the-Stored-Procedure-1024x563.png 1024w, https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Databases-Which-Contains-the-Stored-Procedure-300x165.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Databases-Which-Contains-the-Stored-Procedure-768x423.png 768w, https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Databases-Which-Contains-the-Stored-Procedure.png 1074w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">Now, if you look at the left side of the window, there is Object Explorer. In this explorer, expand the Databases folder, and then within that, you will see all the user-created databases, for example, <strong>Data</strong> and <strong>e-commerce</strong>, in the above picture.</p>



<p class="wp-block-paragraph">As you know, stored procedures are stored in specific databases, so here, understand that you have created a stored procedure under the <strong>e-commerce</strong> databases, so expand this database as shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="507" height="436" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Subfolder-Which-Contains-the-Stored-Procedure.png" alt="Viewing Location of Subfolder Which Contains the Stored Procedure" class="wp-image-20695" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Subfolder-Which-Contains-the-Stored-Procedure.png 507w, https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Location-of-Subfolder-Which-Contains-the-Stored-Procedure-300x258.png 300w" sizes="(max-width: 507px) 100vw, 507px" /></figure>
</div>


<p class="wp-block-paragraph">After expanding the e-commerce databases, you see the different subfolders within it, so your stored procedure exists in the <strong>Programmability</strong> subfolder, as you can see in the above picture.</p>



<p class="wp-block-paragraph">To view the stored procedure, explore the <strong>Programmability</strong> subfolder as shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="309" height="422" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Subfolder-Programmability-Which-Contains-the-Stored-Procedure.png" alt="Viewing Subfolder Programmability Which Contains the Stored Procedure" class="wp-image-20696" style="width:262px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Subfolder-Programmability-Which-Contains-the-Stored-Procedure.png 309w, https://sqlserverguides.com/wp-content/uploads/2024/02/Viewing-Subfolder-Programmability-Which-Contains-the-Stored-Procedure-220x300.png 220w" sizes="(max-width: 309px) 100vw, 309px" /></figure>
</div>


<p class="wp-block-paragraph">When you expand the subfolder <strong>Programmability</strong>, you again see several subfolders; your stored procedures are stored in the subfolder <strong>Stored Procedures</strong>, as you can see in the above picture.</p>



<p class="wp-block-paragraph">To view all the stored procedures of the ecommerce database, expand the subfolder <strong>Stored Procedures</strong> as shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="336" height="164" src="https://sqlserverguides.com/wp-content/uploads/2024/02/How-to-View-Stored-Procedures-in-SQL-Server-using-SQL-Server-Management-Studio.png" alt="SQL Server Management Studio" class="wp-image-20698" style="width:336px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/How-to-View-Stored-Procedures-in-SQL-Server-using-SQL-Server-Management-Studio.png 336w, https://sqlserverguides.com/wp-content/uploads/2024/02/How-to-View-Stored-Procedures-in-SQL-Server-using-SQL-Server-Management-Studio-300x146.png 300w" sizes="(max-width: 336px) 100vw, 336px" /></figure>
</div>


<p class="wp-block-paragraph">Look, the subfolder stored procedures contains two kinds of stored procedures. The first is the system stored procedure in the subfolder System Stored Procedures, and the second is the created stored procedure you can see like <strong>dbo.ProcessOrder</strong> etc.</p>



<p class="wp-block-paragraph">This is how to view the stored procedures in SQL Server using the SQL Server Management Studio.</p>



<h3 class="wp-block-heading">How to View Stored Procedures in SQL Server through Query</h3>



<p class="wp-block-paragraph">From the above section, you learned how to view stored procedures using the SSMS; here, I will show how to do the same using the query.</p>



<p class="wp-block-paragraph">So, here, multiple ways exist to view stored procedures in SQL Server through query.</p>



<p class="wp-block-paragraph">First, open your computer&#8217;s query editor or SQL server command prompt, where you can execute the SQL Server query.</p>



<h4 class="wp-block-heading">View Stored Procedures in SQL Server through Query using sp_helptext</h4>



<p class="wp-block-paragraph">There is a system-stored procedure called <strong>sp_helptext</strong>, which can help you view the stored procedures. This will not list all the stored procedures. Instead, you can use it to view specific stored procedures.</p>



<p class="wp-block-paragraph">For example, the ecommerce database contains the <strong>ProcessOrder</strong> stored procedure. You can view it using the <strong>sp_helptext</strong> system procedure, as shown below.</p>



<pre class="wp-block-code"><code>EXEC sp_helptext ProcessOrder;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="503" height="379" src="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-sp_helptext.png" alt="View Stored Procedures in SQL Server Through Query using sp_helptext" class="wp-image-20704" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-sp_helptext.png 503w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-sp_helptext-300x226.png 300w" sizes="(max-width: 503px) 100vw, 503px" /></figure>
</div>


<p class="wp-block-paragraph">It shows all the statements or how the <strong>ProcessOrder</strong> stored procedure is created. Well, this <strong>sp_helptext</strong> is used to view the created stored procedure. Generally, it shows the script of the specified stored procedures.</p>



<p class="wp-block-paragraph">This is how to view stored procedures in SQL Server through query using sp_helptext.</p>



<h4 class="wp-block-heading">View Stored Procedures in SQL Server through Query using sys.sql_modules</h4>



<p class="wp-block-paragraph">Next is the <strong>sys.sql_modules</strong> system view, which contains a row for each object implemented as an SQL module, including stored procedures.</p>



<p class="wp-block-paragraph">Use the below query to view all the stored procedures in the current database.</p>



<pre class="wp-block-code"><code>SELECT m.definition
FROM sys.sql_modules m
JOIN sys.objects o ON m.object_id = o.object_id
WHERE o.type = 'P'</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="746" height="335" src="https://sqlserverguides.com/wp-content/uploads/2024/02/View-All-Stored-Procedures-in-SQL-Server-Through-Query-using-sp_helptext.png" alt="View All Stored Procedures in SQL Server Through Query using sp_helptext" class="wp-image-20710" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/View-All-Stored-Procedures-in-SQL-Server-Through-Query-using-sp_helptext.png 746w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-All-Stored-Procedures-in-SQL-Server-Through-Query-using-sp_helptext-300x135.png 300w" sizes="(max-width: 746px) 100vw, 746px" /></figure>
</div>


<p class="wp-block-paragraph">Look, it returns all the stored procedures in the current database but as definition. This is how you can view all the stored procedures in the current database and the specified stored procedure definition.</p>



<p class="wp-block-paragraph">Use the below query to view the <strong>ProcessOrder</strong> stored procedure definition.</p>



<pre class="wp-block-code"><code>SELECT m.definition
FROM sys.sql_modules m
JOIN sys.objects o ON m.object_id = o.object_id
WHERE o.type = 'P' AND o.name = 'ProcessOrder';</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="907" height="355" src="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-sys.sql_modules.png" alt="View Stored Procedures in SQL Server Through Query using sys.sql_modules" class="wp-image-20707" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-sys.sql_modules.png 907w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-sys.sql_modules-300x117.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-sys.sql_modules-768x301.png 768w" sizes="(max-width: 907px) 100vw, 907px" /></figure>
</div>


<p class="wp-block-paragraph">From the output, as you can see, the <strong>sys.sql_modules</strong> view allows us to view the complete definition of the specified stored procedure.</p>



<p class="wp-block-paragraph">This is how to view stored procedures in SQL Server through query using the <strong>sys.sql_modules</strong> system view.</p>



<h4 class="wp-block-heading">View Stored Procedures in SQL Server through Query using INFORMATION_SCHEMA.ROUTINES</h4>



<p class="wp-block-paragraph">The SQL Server has another view called <strong>INFORMATION_SHCEMA.ROUTINES</strong> contain information about all the stored procedures.</p>



<p class="wp-block-paragraph">To view all the stored procedures, execute the below query.</p>



<pre class="wp-block-code"><code>SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE';
</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="644" height="299" src="https://sqlserverguides.com/wp-content/uploads/2024/02/View-All-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES.png" alt="View All Stored Procedures in SQL Server Through Query using INFORMATION_SCHEMA.ROUTINES" class="wp-image-20714" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/View-All-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES.png 644w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-All-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES-300x139.png 300w" sizes="(max-width: 644px) 100vw, 644px" /></figure>
</div>


<p class="wp-block-paragraph">Now, it is the <strong>INFORMATION_SCHEMA.ROUTINES all the store</strong>d procedures in the current database that you can see in the query output; look at the column <strong>ROUTINE_NAME</strong>, which contains procedure names such as <strong>usp_GetEmployees</strong>, <strong>ProcessOrder</strong>, etc.</p>



<p class="wp-block-paragraph">Also, you can view the specified stored procedure using the query below.</p>



<pre class="wp-block-code"><code>SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = 'UpdateEmployeeDetails';
</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="248" src="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES-1024x248.png" alt="View Stored Procedures in SQL Server Through Query using INFORMATION_SCHEMA.ROUTINES" class="wp-image-20716" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES-1024x248.png 1024w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES-300x73.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES-768x186.png 768w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-Through-Query-using-INFORMATION_SCHEMA.ROUTINES.png 1162w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">So, it returned the two columns, <strong>ROUTINE_NAME and ROUTINE_DEFINITION</strong>, which contain the stored procedure name and its definition, respectively.</p>



<p class="wp-block-paragraph">This is how to view stored procedures in SQL Server through query using  <strong>INFORMATION_SCHEMA.ROUTINES</strong> view.</p>



<h4 class="wp-block-heading">View Stored Procedures in SQL Server through Query using OBJECT_DEFINTION</h4>



<p class="wp-block-paragraph">SQL Server has a function called OBJECT_DEFINTION, which returns the SQL source text of the stored procedure if you know the object ID.</p>



<p class="wp-block-paragraph">Same as <strong>sp_helptext,</strong> it returns the script of the stored procedure.</p>



<pre class="wp-block-code"><code>SELECT OBJECT_DEFINITION(OBJECT_ID('ProcessOrder'));</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="813" height="176" src="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-through-Query-using-OBJECT_DEFINTION.png" alt="View Stored Procedures in SQL Server through Query using OBJECT_DEFINTION" class="wp-image-20719" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-through-Query-using-OBJECT_DEFINTION.png 813w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-through-Query-using-OBJECT_DEFINTION-300x65.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/View-Stored-Procedures-in-SQL-Server-through-Query-using-OBJECT_DEFINTION-768x166.png 768w" sizes="(max-width: 813px) 100vw, 813px" /></figure>
</div>


<p class="wp-block-paragraph">The output returns the definition or script of the <strong>ProcesOrder</strong> stored procedure. Here, you have to pass the stored procedure name to <strong>OBJECT_ID()</strong>, which receives the object ID of the specified stored procedure.</p>



<p class="wp-block-paragraph">Then, this returned object is passed to the <strong>OBJECT_DEFINITION()</strong> function to view them. That is why the <strong>OJBECT_ID()</strong> function is passed to the <strong>OBJECT_DEFINITION()</strong> function.</p>



<p class="wp-block-paragraph">This is how to view a specific definition of stored procedure in SQL Server.</p>



<p class="wp-block-paragraph">I hope you understand how to find the stored procedure and its definition in SQL Server.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">You learned to view stored procedures in SQL Server using the SSMS and Query.</p>



<p class="wp-block-paragraph">Where you have used the different stored procedures and functions to view the stored procedure, you also learned to view a specific stored procedure using the sp_helptext and OBJECT_DEFINTION().</p>



<p class="wp-block-paragraph">You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/how-to-alter-stored-procedure-in-sql-server/">How to Alter Stored Procedure in SQL Server</a></li>



<li><a href="https://sqlserverguides.com/create-sql-server-stored-procedure-default-parameter/">Create SQL Server Stored Procedure Default Parameter</a></li>



<li><a href="https://sqlserverguides.com/sql-server-call-stored-procedure-from-another-stored-procedure/">SQL Server Call Stored Procedure from another Stored Procedure</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Alter Stored Procedure in SQL Server</title>
		<link>https://sqlserverguides.com/how-to-alter-stored-procedure-in-sql-server/</link>
		
		<dc:creator><![CDATA[Bijay Kumar Sahoo]]></dc:creator>
		<pubDate>Mon, 04 Mar 2024 13:44:09 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Alter Stored Procedure in SQL Server]]></category>
		<guid isPermaLink="false">https://sqlserverguides.com/?p=20743</guid>

					<description><![CDATA[In this SQL Server tutorial, I will teach you how to alter stored procedure in SQL Server. As a Database developer, administrator, etc., you should know how to modify the existing stored procedure. I will start by explaining why to change the existing stored procedure, then the syntax you can use to modify the stored ... <a title="How to Alter Stored Procedure in SQL Server" class="read-more" href="https://sqlserverguides.com/how-to-alter-stored-procedure-in-sql-server/" aria-label="Read more about How to Alter Stored Procedure in SQL Server">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this SQL Server tutorial, <strong>I will teach you how to alter stored procedure in SQL Server.</strong></p>



<p class="wp-block-paragraph">As a Database developer, administrator, etc., you should know how to modify the existing stored procedure.</p>



<p class="wp-block-paragraph">I will start by explaining why to change the existing stored procedure, then the syntax you can use to modify the stored procedure. </p>



<p class="wp-block-paragraph">Here, I will explain two types of syntax: <strong>one that allows you to modify the stored procedure of existing public schema</strong> and the <strong>other that will enable you to modify the stored procedure of specific schema.</strong></p>



<p class="wp-block-paragraph">Finally, with examples, you will see how to create and alter or modify the stored procedure in a specific schema.</p>



<h2 class="wp-block-heading">Alter Stored Procedure in SQL Server</h2>



<p class="wp-block-paragraph">As you know, the stored procedure contains the set of logic or operations, and you can reuse the stored procedure anywhere or wherever it is required.</p>



<p class="wp-block-paragraph">Sometimes, requirements arise due to changes in the business, so in that situation, you also need to change some existing stored procedures. So SQL Server provides <strong>ALTER PROCEDURE</strong> command to modify the existing stored procedure without dropping or recreating them.</p>



<p class="wp-block-paragraph">The syntax is given below.</p>



<pre class="wp-block-code"><code>ALTER PROCEDURE procedure_name &#91; @parameter data_type ]
    &#91; WITH { RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION } ]
AS
BEGIN
    -- SQL statements to define the procedure logic
END</code></pre>



<p class="wp-block-paragraph">Where,</p>



<ul class="wp-block-list">
<li><strong>ALTER PROCEDURE: </strong>It is the command to modify the specific stored procedure.</li>



<li><strong>procedure_name:</strong> Name of the stored procedure that you want to modify.</li>



<li><strong>@parameter data_type:</strong> It is the parameter and its data type that the stored procedure will accept, but it is optional.</li>



<li><strong>WITH RECOMPILE: </strong>Using this forces the procedure to compile at runtime, which is beneficial for those not executed continually.</li>



<li><strong>WITH ENCRIPTION:</strong> If you use this, it encrypts the contents of the procedure in the database, which doesn&#8217;t allow the user to view its logic.</li>
</ul>



<p class="wp-block-paragraph">Also, look at the syntax below if you have stored a procedure in a specific scheme, then use the syntax below to alter that stored procedure.</p>



<pre class="wp-block-code"><code>ALTER PROCEDURE <strong>schema_name.procedure_name</strong> &#91; @parameter data_type ]
    &#91; WITH { RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION } ]
AS
BEGIN
    -- SQL statements to define the procedure logic
END</code></pre>



<p class="wp-block-paragraph">Here, you need to make small changes; prefix the procedure_name with schema_name, such as <strong>schema_name.procedure_name.</strong></p>



<p class="wp-block-paragraph">Let&#8217;s take an example and see how to create and alter the stored procedure.</p>



<h3 class="wp-block-heading">Creating Stored Procedure</h3>



<p class="wp-block-paragraph">So here, I have the Employees table, shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="460" height="486" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-Employees-Table.png" alt="Alter Stored Procedure in SQL Server Employees Table" class="wp-image-20745" style="width:345px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-Employees-Table.png 460w, https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-Employees-Table-284x300.png 284w" sizes="(max-width: 460px) 100vw, 460px" /></figure>
</div>


<p class="wp-block-paragraph">Now, create a stored procedure named <strong>GetEmployeesOnSalary;</strong> this procedure will return the EmployeesID of the employees whose salary is greater than a certain amount.</p>



<pre class="wp-block-code"><code>CREATE PROCEDURE GetEmployeesOnSalary (@salary INT)
AS
BEGIN
	SELECT EmployeeID FROM Employees 
	WHERE Salary &gt; @salary;
END;</code></pre>



<p class="wp-block-paragraph">Executing the above query creates a new stored procedure, <strong>GetEmployeesOnSalary</strong>, in your database.</p>



<p class="wp-block-paragraph">Let&#8217;s check this procedure or execute it with a value equal to 60000 to check the employees whose salary exceeds 60000.</p>



<pre class="wp-block-code"><code>EXEC GetEmployeesOnSalary 60000;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="834" height="622" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Checking-the-Stored-Procedure-with-Parameter-Value.png" alt="Checking the Stored Procedure with Parameter Value" class="wp-image-20747" style="width:629px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Checking-the-Stored-Procedure-with-Parameter-Value.png 834w, https://sqlserverguides.com/wp-content/uploads/2024/02/Checking-the-Stored-Procedure-with-Parameter-Value-300x224.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/Checking-the-Stored-Procedure-with-Parameter-Value-768x573.png 768w" sizes="(max-width: 834px) 100vw, 834px" /></figure>
</div>


<p class="wp-block-paragraph">When you execute the <strong>GetEmployeesOnSalary</strong> with a value of 60000, it returns all the employees whose salaries are greater than 60000 dollars.</p>



<p class="wp-block-paragraph">Let&#8217;s say you have a task where you must include an employee&#8217;s name. That means you have to alter the procedure so that it should also return the employee with their name. Here, you can use the <strong>ALTER PROCEDURE</strong> command to modify the procedure.</p>



<pre class="wp-block-code"><code>ALTER PROCEDURE GetEmployeesOnSalary (@salary INT)
AS
BEGIN
	SELECT EmployeeID, Name FROM Employees 
	WHERE Salary &gt; @salary;
END;</code></pre>



<p class="wp-block-paragraph">When you run the above query, it modifies the <strong>GetEmployeesOnSalary </strong>to include the <strong>&#8216;Name&#8217;</strong> column in the <strong>SELECT</strong> statement without dropping and recreating the procedure.</p>



<p class="wp-block-paragraph">Now, let&#8217;s execute the stored procedure again with the value 65000, as shown below.</p>



<pre class="wp-block-code"><code>EXEC GetEmployeesOnSalary 65000;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="824" height="547" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server.png" alt="Alter Stored Procedure in SQL Server" class="wp-image-20753" style="width:637px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server.png 824w, https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-300x199.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-768x510.png 768w" sizes="(max-width: 824px) 100vw, 824px" /></figure>
</div>


<p class="wp-block-paragraph">As you have modified the procedure, it returns the result in the same way as it also includes the employee name whose salary is greater than 65000 dollars.</p>



<p class="wp-block-paragraph">Here, you have modified the stored procedure to add the column, but you can even add an additional parameter, logic, etc, to the stored procedure. It depends on what kind of modification you want.</p>



<h3 class="wp-block-heading">Alter Stored Procedure in SQL Server of Specific Schema</h3>



<p class="wp-block-paragraph">Here, I will demonstrate how to alter the stored procedure in the specified schema in your database.</p>



<p class="wp-block-paragraph">For example, there is a table SalesTransaction in the schema Sales, as shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="680" height="352" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema-Table-Tansactions.png" alt="Alter Stored Procedure in SQL Server of Specific Schema Table Tansactions" class="wp-image-20759" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema-Table-Tansactions.png 680w, https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema-Table-Tansactions-300x155.png 300w" sizes="(max-width: 680px) 100vw, 680px" /></figure>
</div>


<p class="wp-block-paragraph">As you can see, the <strong>SalesTransaction</strong> table exists in the <strong>Sales</strong> schema; let&#8217;s create a stored procedure that will return the sale amount based on the specified <strong>TaxRate</strong>.</p>



<pre class="wp-block-code"><code>CREATE PROCEDURE Sales.GetTransactioOnTaxRate (@taxrate NUMERIC(10,2))
AS
BEGIN
	SELECT SaleAmount FROM Sales.SalesTransactions 
	WHERE TaxRate = @taxrate;
END;</code></pre>



<p class="wp-block-paragraph">When you execute the above command, it creates a new stored procedure, <strong>GetTransactioOnTaxRate,</strong> in the schema <strong>Sales</strong> of the current database.</p>



<p class="wp-block-paragraph">Let&#8217;s execute the stored procedure with a tax rate value 5.0, as shown below.</p>



<pre class="wp-block-code"><code>EXEC Sales.GetTransactioOnTaxRate 5.0;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="395" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-in-SQL-Server-of-Specific-Schema-1024x395.png" alt="Executing Stored Procedure in SQL Server of Specific Schema" class="wp-image-20764" style="width:767px;height:auto" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-in-SQL-Server-of-Specific-Schema-1024x395.png 1024w, https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-in-SQL-Server-of-Specific-Schema-300x116.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-in-SQL-Server-of-Specific-Schema-768x296.png 768w, https://sqlserverguides.com/wp-content/uploads/2024/02/Executing-Stored-Procedure-in-SQL-Server-of-Specific-Schema.png 1095w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">As you can see, it returns the sale amount of the transaction based on the tax rate 5.0. But as you can see, it is not meaningful, which means which transaction this sale amount belongs to.</p>



<p class="wp-block-paragraph">So here, you have been assigned a task to alter the stored procedure <strong>GetTransactioOnTaxRate</strong> to include the transaction ID. Use the below command to modify the stored procedure.</p>



<pre class="wp-block-code"><code>ALTER PROCEDURE Sales.GetTransactioOnTaxRate (@taxrate NUMERIC(10,2))
AS
BEGIN
	SELECT TransactionID, SaleAmount FROM Sales.SalesTransactions 
	WHERE TaxRate = @taxrate;
END;</code></pre>



<p class="wp-block-paragraph">After executing the above command, it modifies the <strong>Sales.GetTransactioOnTaxRate</strong> to include the <strong>&#8216;TransactionID&#8217;</strong> column in the <strong>SELECT</strong> statement without dropping and recreating the procedure.</p>



<p class="wp-block-paragraph">Here, you can see the statement <strong>ALTER PROCEDURE Sales.GetTransactioOnTaxRate</strong>, altering the stored procedure GetTransactioOnTaxRate of the Sales schema.</p>



<p class="wp-block-paragraph">Now execute the modified stored procedure with a tax rate of 8.0, as shown below.</p>



<pre class="wp-block-code"><code>EXEC Sales.GetTransactioOnTaxRate 8.0;</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="406" src="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema-1024x406.png" alt="Alter Stored Procedure in SQL Server of Specific Schema" class="wp-image-20767" srcset="https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema-1024x406.png 1024w, https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema-300x119.png 300w, https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema-768x305.png 768w, https://sqlserverguides.com/wp-content/uploads/2024/02/Alter-Stored-Procedure-in-SQL-Server-of-Specific-Schema.png 1048w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">From the output, it included the transaction ID with the sale amount of the specified text rate value.</p>



<p class="wp-block-paragraph">This is how you can alter stored procedures in SQL Server. I hope you now understand how to modify the stored procedure.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">You learned how to alter stored procedure in SQL Server, where you have used the ALTER PROCEDURE command to modify the stored procedure.</p>



<p class="wp-block-paragraph">Especially you learned how to include a column in the <strong>SELECT</strong> statement within the stored procedure, but you can modify the procedure name, logic, etc., using the <strong>ALTER PROCEDURE</strong> command.</p>



<p class="wp-block-paragraph">You learned how to create and modify the stored procedure in the public and specific database schema.</p>



<p class="wp-block-paragraph">You may like to read:</p>



<ul class="wp-block-list">
<li><a href="https://sqlserverguides.com/create-sql-server-stored-procedure-default-parameter/">Create SQL Server Stored Procedure Default Parameter</a></li>



<li><a href="https://sqlserverguides.com/sql-server-call-stored-procedure-from-another-stored-procedure/">SQL Server Call Stored Procedure from another Stored Procedure</a></li>



<li><a href="https://sqlserverguides.com/how-to-test-stored-procedures-in-sql-server/">How to Test Stored Procedures in SQL Server</a></li>
</ul>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Bijay Kumar Sahoo' src='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/18a79d27129a98c6530098c50aef09aa901fced58315025237441af82a0fa179?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://sqlserverguides.com/author/fewlines4biju/" class="vcard author" rel="author"><span class="fn">Bijay Kumar Sahoo</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a <a href="https://mvp.microsoft.com/en-us/PublicProfile/5000972" rel="noopener" target="_blank">Microsoft MVP</a>. Check out more <a href="https://sqlserverguides.com/about/" rel="noopener">here</a>.</p>
</div></div><div class="saboxplugin-web "><a href="https://sqlserverguides.com" target="_self">sqlserverguides.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Facebook" target="_self" href="https://www.facebook.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a><a title="Linkedin" target="_self" href="https://www.linkedin.com/in/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-linkedin" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 448 512"><path fill="currentColor" d="M100.3 480H7.4V180.9h92.9V480zM53.8 140.1C24.1 140.1 0 115.5 0 85.8 0 56.1 24.1 32 53.8 32c29.7 0 53.8 24.1 53.8 53.8 0 29.7-24.1 54.3-53.8 54.3zM448 480h-92.7V334.4c0-34.7-.7-79.2-48.3-79.2-48.3 0-55.7 37.7-55.7 76.7V480h-92.8V180.9h89.1v40.8h1.3c12.4-23.5 42.7-48.3 87.9-48.3 94 0 111.3 61.9 111.3 142.3V480z"></path></svg></span></a><a title="Twitter" target="_self" href="https://twitter.com/fewlines4biju" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Pinterest" target="_self" href="https://in.pinterest.com/fewlines4biju/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-pinterest" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 496 512"><path fill="currentColor" d="M496 256c0 137-111 248-248 248-25.6 0-50.2-3.9-73.4-11.1 10.1-16.5 25.2-43.5 30.8-65 3-11.6 15.4-59 15.4-59 8.1 15.4 31.7 28.5 56.8 28.5 74.8 0 128.7-68.8 128.7-154.3 0-81.9-66.9-143.2-152.9-143.2-107 0-163.9 71.8-163.9 150.1 0 36.4 19.4 81.7 50.3 96.1 4.7 2.2 7.2 1.2 8.3-3.3.8-3.4 5-20.3 6.9-28.1.6-2.5.3-4.7-1.7-7.1-10.1-12.5-18.3-35.3-18.3-56.6 0-54.7 41.4-107.6 112-107.6 60.9 0 103.6 41.5 103.6 100.9 0 67.1-33.9 113.6-78 113.6-24.3 0-42.6-20.1-36.7-44.8 7-29.5 20.5-61.3 20.5-82.6 0-19-10.2-34.9-31.4-34.9-24.9 0-44.9 25.7-44.9 60.2 0 22 7.4 36.8 7.4 36.8s-24.5 103.8-29 123.2c-5 21.4-3 51.6-.9 71.2C65.4 450.9 0 361.1 0 256 0 119 111 8 248 8s248 111 248 248z"></path></svg></span></a></div></div></div>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: sqlserverguides.com @ 2026-07-08 00:07:32 by W3 Total Cache
-->