<?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/"
	>

<channel>
	<title>Stored Procedures - MSSQL Query</title>
	<atom:link href="https://mssqlquery.com/category/stored-procedures/feed" rel="self" type="application/rss+xml" />
	<link>https://mssqlquery.com</link>
	<description>MSSQL and TSQL Programming and TSQL Examples</description>
	<lastBuildDate>Thu, 25 May 2023 09:57:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.3.1</generator>

<image>
	<url>https://mssqlquery.com/wp-content/uploads/2023/06/cropped-mssql-query-icon-32x32.png</url>
	<title>Stored Procedures - MSSQL Query</title>
	<link>https://mssqlquery.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Customized PRINT Procedure in SQL Server</title>
		<link>https://mssqlquery.com/customized-print-procedure-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Thu, 25 May 2023 09:57:10 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[PRINT Procedure]]></category>
		<category><![CDATA[SQL PRINT 4000]]></category>
		<category><![CDATA[SQL Server PRINT]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1578</guid>

					<description><![CDATA[<p>Hello everyone. In this article, I will try to give information about the customized PRINT procedure in SQL Server. In SQL Server, the PRINT statement prints up to 4000 characters. So what will you do if the content of the dynamic queries you write is longer than 4000 characters? In&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/customized-print-procedure-in-sql-server">Customized PRINT Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone. In this article, I will try to give information about the customized PRINT procedure in SQL Server.</p>
<p>In SQL Server, the PRINT statement prints up to 4000 characters. So what will you do if the content of the dynamic queries you write is longer than 4000 characters?</p>
<p>In SQL Server, in some cases, you may want to PRINT statements with more than 4000 characters.</p>
<p>You can easily do this using the procedure below.</p>
<pre class="line-numbers"><code class="language-sql">CREATE PROCEDURE LONGPRINT
    @String NVARCHAR(MAX)
AS
BEGIN
    BEGIN TRY

    DECLARE @CurrentEnd BIGINT;
    DECLARE @Offset TINYINT; 
    SET @String = replace(replace(@String, CHAR(13) + CHAR(10), CHAR(10)), CHAR(13), CHAR(10))

    WHILE LEN(@String) &gt; 1
    BEGIN
        IF CHARINDEX(CHAR(10), @String) BETWEEN 1 AND 4000
        BEGIN
            SET @CurrentEnd =  CHARINDEX(CHAR(10), @String) -1
            SET @Offset = 2
        END
        ELSE
        BEGIN
            SET @CurrentEnd = 4000
            SET @Offset = 1
        END   
        PRINT SUBSTRING(@String, 1, @CurrentEnd) 
        SET @String = SUBSTRING(@String, @CurrentEnd + @Offset, LEN(@String))   
    END 
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage VARCHAR(4000)
        SELECT @ErrorMessage = ERROR_MESSAGE()    
        RAISERROR(@ErrorMessage,16,1)
    END CATCH
END

--Use of the Procedure

DECLARE @Degisken VARCHAR(MAX)
SET @Degisken = REPLICATE('x', 6000)
EXEC LONGPRINT @Degisken</code></pre>
<p>When you create the above procedure and run the code, you will see a result similar to the one below.</p>
<p><img decoding="async" fetchpriority="high" class="alignnone wp-image-1581 size-full" src="https://mssqlquery.com/wp-content/uploads/2023/05/customized-print-procedure-in-sql-server-1.jpg" alt="Customized PRINT Procedure in SQL Server" width="700" height="357" srcset="https://mssqlquery.com/wp-content/uploads/2023/05/customized-print-procedure-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2023/05/customized-print-procedure-in-sql-server-1-300x153.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, we have printed 6000 characters with the LONGPRINT procedure.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 29</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/customized-print-procedure-in-sql-server">Customized PRINT Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Why You Shouldn&#8217;t Prefix &#8220;sp_&#8221; Before Your Stored Procedures in SQL Server?</title>
		<link>https://mssqlquery.com/why-you-shouldnt-prefix-sp_-before-your-stored-procedures-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Mon, 22 May 2023 19:51:23 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[sp_ prefix]]></category>
		<category><![CDATA[SQL Server sp_ prefix]]></category>
		<category><![CDATA[Stored Procedures in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1575</guid>

					<description><![CDATA[<p>Hello everyone. In this article, I will try to give information about why you should not add &#8220;sp_&#8221; prefix in front of your Stored Procedures in SQL Server. Most people tend to prefix &#8220;sp_&#8221; to the name of the Stored Procedure when creating a Stored Procedure in SQL Server. There&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/why-you-shouldnt-prefix-sp_-before-your-stored-procedures-in-sql-server">Why You Shouldn’t Prefix “sp_” Before Your Stored Procedures in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone. In this article, I will try to give information about why you should not add &#8220;sp_&#8221; prefix in front of your Stored Procedures in SQL Server.</p>
<p>Most people tend to prefix &#8220;sp_&#8221; to the name of the Stored Procedure when creating a Stored Procedure in SQL Server.</p>
<p>There are several reasons why this is considered bad practice.</p>
<p><strong>Microsoft says you shouldn&#8217;t do this.</strong></p>
<p>You can read Microsoft&#8217;s statement below.</p>
<p>Avoid using the sp_ prefix when naming Stored Procedures. This prefix is used by Microsoft SQL Server to identify system procedures. Using the prefix can break the application code if there is a system procedure with the same name.</p>
<p>This means that if you accidentally name your Stored Procedure with the same name as one of SQL Server&#8217;s Stored Procedure, your Stored Procedure will not be called. Instead, the SQL Server System Stored Procedure is called.</p>
<p>For example, if you have created a Stored Procedure named &#8220;sp_configure&#8221; in your database, it will never be executed when you call it because there is a system Stored Procedure named &#8220;sp_configure&#8221; in the master database and will be called instead.</p>
<p>Second, when SQL Server sees the prefix &#8220;sp_&#8221; at the beginning of a Stored Procedure, it first tries to find that procedure in the master database. As stated in the Microsoft documentation above, &#8221; This prefix is used by SQL Server to denote system procedures &#8220;, so when SQL Server sees the phrase &#8220;sp_&#8221; prefix, it starts searching for system procedures. But after searching all the procedures in the master database and determining that your procedure is not there, it will return to your database to try to find the stored procedure.</p>
<p>As noted in the above post, procedures named with the “sp_” prefix will run slower. Of course, this may not always be noticed.</p>
<p>There are times when the above situation is an exception.</p>
<pre class="line-numbers"><code class="language-markup">Use DatabaseOrnek 
EXEC dbo.sp_configure</code></pre>
<p>ile</p>
<pre class="line-numbers"><code class="language-markup">Use DatabaseOrnek 
EXEC DatabaseOrnek.dbo.sp_configure</code></pre>
<p>The second example will call your procedure correctly.</p>
<p>But for this to work, you have to call it like (databasename.semaname.procedure) every time.</p>
<p>Unless you are intentionally creating a Stored Procedure in the SQL Server system database, there is no valid reason to name the Stored Procedure with the &#8220;sp_&#8221; prefix. It is not very convenient to send SQL Server to wrong database to find Stored Procedure. It&#8217;s confusing, inefficient, and can cause performance issues. So why take the risk? To help maintain peak performance of your databases, avoid using the &#8220;sp_&#8221; prefix in your Stored Procedure names.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 32</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/why-you-shouldnt-prefix-sp_-before-your-stored-procedures-in-sql-server">Why You Shouldn’t Prefix “sp_” Before Your Stored Procedures in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Procedure to Output Tables in HTML Format in SQL Server</title>
		<link>https://mssqlquery.com/procedure-to-output-tables-in-html-format-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Mon, 03 Apr 2023 05:33:48 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[SQL HTML Format]]></category>
		<category><![CDATA[SQL Server HTML Format]]></category>
		<category><![CDATA[sql server procedure]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1484</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will share information about the procedure for outputting tables in HTML format in SQL Server In SQL Server, in some cases you may want to output the tables in HTML format. You can easily do this by using the following procedure. CREATE PROCEDURE [dbo].[SqlTableToHtml]&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/procedure-to-output-tables-in-html-format-in-sql-server">Procedure to Output Tables in HTML Format in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will share information about the procedure for outputting tables in HTML format in SQL Server</p>
<p>In SQL Server, in some cases you may want to output the tables in HTML format.</p>
<p>You can easily do this by using the following procedure.</p>
<pre class="line-numbers"><code class="language-sql">CREATE PROCEDURE [dbo].[SqlTableToHtml] (@TABLENAME NVARCHAR(500),
@OUTPUT NVARCHAR(MAX) OUTPUT,
@TBL_STYLE NVARCHAR(1024) = '',
@TD_STYLE NVARCHAR(1024) = '',
@HDR_STYLE NVARCHAR(1024) = '')
AS

	DECLARE @exec_str NVARCHAR(MAX)
	DECLARE @ParmDefinition NVARCHAR(500)

	SET @exec_str = N'
DECLARE @exec_str  NVARCHAR(MAX)
DECLARE @ParmDefinition NVARCHAR(500)

select CustColHTML_ID=0,* INTO #CustomTable2HTML FROM ' + @TABLENAME + ' 

DECLARE @COUNTER INT
SET @COUNTER=0
UPDATE #CustomTable2HTML SET @COUNTER = CustColHTML_ID=@COUNTER+1 

DECLARE @HTMLROWS NVARCHAR(MAX) DECLARE @FIELDS NVARCHAR(MAX) 
SET @HTMLROWS='''' DECLARE @ROW NVARCHAR(MAX) 

SET @FIELDS=''&lt;tr&gt;''
SELECT @FIELDS=COALESCE(@FIELDS, '' '','''')+''&lt;th ' + @HDR_STYLE + '&gt;'' + name + ''&lt;/th&gt;''
FROM tempdb.sys.Columns
WHERE object_id=object_id(''tempdb..#CustomTable2HTML'')
AND name not like ''CustColHTML_ID''
SET @FIELDS=@FIELDS + ''&lt;/tr&gt;''

DECLARE @ColumnName  NVARCHAR(500)
DECLARE @maxrows INT
DECLARE @rownum INT

--Find row count of our temporary table
SELECT @maxrows=count(*) FROM  #CustomTable2HTML

DECLARE col CURSOR FOR
SELECT name FROM tempdb.sys.Columns
WHERE object_id=object_id(''tempdb..#CustomTable2HTML'')
AND name not like ''CustColHTML_ID''
ORDER BY column_id ASC

SET @rowNum=0
SET @ParmDefinition=N''@ROWOUT NVARCHAR(MAX) OUTPUT,@rowNum_IN INT''

While @rowNum &lt; @maxrows
BEGIN
  SET @HTMLROWS=@HTMLROWS + ''&lt;tr&gt;''

  SET @rowNum=@rowNum +1
  OPEN col
  FETCH NEXT FROM col INTO @ColumnName
  WHILE @@FETCH_STATUS=0
    BEGIN
      SET @exec_str=''SELECT @ROWOUT=(select COALESCE(['' + @ColumnName + ''], '''''''') AS ['' + @ColumnName + ''] from #CustomTable2HTML where CustColHTML_ID=@rowNum_IN)''

	  EXEC	sp_executesql 
			@exec_str,
			@ParmDefinition,
			@ROWOUT=@ROW OUTPUT,
            @rowNum_IN=@rownum

      SET @HTMLROWS =@HTMLROWS +  ''&lt;td ' + @TD_STYLE + '&gt;'' + @ROW + ''&lt;/td&gt;''
      FETCH NEXT FROM col INTO @ColumnName
    END
  CLOSE col
  SET @HTMLROWS=@HTMLROWS + ''&lt;/tr&gt;''
END

SET @OUTPUT=''''
IF @maxrows&gt;0
SET @OUTPUT= ''&lt;table ' + @TBL_STYLE + '&gt;'' + @FIELDS + @HTMLROWS + ''&lt;/table&gt;''

DEALLOCATE col
'

	DECLARE @ParamDefinition NVARCHAR(MAX)
	SET @ParamDefinition = N'@OUTPUT NVARCHAR(MAX) OUTPUT'
	EXEC sp_executesql @exec_str
					  ,@ParamDefinition
					  ,@OUTPUT = @OUTPUT OUTPUT

	RETURN 1


--Use of the Procedure


DECLARE @html NVARCHAR(MAX)
EXEC SqlTableToHtml 'Products'
					,@html OUTPUT
					,''
					,'style="border-top:1px #CCCCCC solid;padding:7px"'
					,'style="padding:7px"'
SELECT
	@html</code></pre>
<p>Create and run the above procedure and you will see a result similar to the one below.</p>
<p><img decoding="async" class="alignnone wp-image-1487 size-full" src="https://mssqlquery.com/wp-content/uploads/2023/04/procedure-to-output-tables-in-html-format-in-sql-server-1.jpg" alt="Procedure to Output Tables in HTML Format in SQL Server" width="700" height="416" srcset="https://mssqlquery.com/wp-content/uploads/2023/04/procedure-to-output-tables-in-html-format-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2023/04/procedure-to-output-tables-in-html-format-in-sql-server-1-300x178.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>I got the result by trying the above procedure on the Products table on the Northwind database. You can also try it on your own tables.</p>
<p>As you can see, we have printed the table in HTML format.</p>
<p>Good luck to everyone in their working life and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 41</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/procedure-to-output-tables-in-html-format-in-sql-server">Procedure to Output Tables in HTML Format in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>When to Use the sp_refreshview Procedure in SQL Server</title>
		<link>https://mssqlquery.com/when-to-use-the-sp_refreshview-procedure-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Sun, 02 Apr 2023 10:57:50 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[sp_refreshview]]></category>
		<category><![CDATA[sp_refreshview Procedure]]></category>
		<category><![CDATA[sp_refreshview Procedure in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1475</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will give you information about when to use the sp_refreshview procedure in SQL Server. The sp_refreshview procedure in SQL Server is used to update the metadata of a view in the database. This can be necessary in certain situations, such as when a view&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/when-to-use-the-sp_refreshview-procedure-in-sql-server">When to Use the sp_refreshview Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will give you information about when to use the sp_refreshview procedure in SQL Server.</p>
<p>The sp_refreshview procedure in SQL Server is used to update the metadata of a view in the database. This can be necessary in certain situations, such as when a view is not returning the expected results, or when changes have been made to the underlying tables or columns that are referenced by the view.</p>
<p>Here are some situations when you might want to use sp_refreshview:</p>
<ol>
<li><strong>After altering a table or view referenced by the view:</strong> If you make changes to a table or view that is used in the definition of a view, you will need to refresh the view&#8217;s metadata using sp_refreshview so that it reflects the changes.</li>
<li><strong>After restoring a database:</strong> If you restore a database that contains views, you should refresh the metadata of those views using sp_refreshview so that they reflect the current state of the database.</li>
<li><strong>When troubleshooting view performance issues:</strong> If you are experiencing performance issues with a view, you can use sp_refreshview to update its metadata and ensure that it is using the most up-to-date statistics.</li>
</ol>
<p>In general, sp_refreshview is not needed on a regular basis, but it can be useful in certain situations to ensure that your views are up-to-date and functioning as expected.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 86</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/when-to-use-the-sp_refreshview-procedure-in-sql-server">When to Use the sp_refreshview Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Finding the Physical Size of a Table in SQL Server</title>
		<link>https://mssqlquery.com/finding-the-physical-size-of-a-table-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Sat, 18 Mar 2023 18:25:32 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Physical Size of a Table in SQL Server]]></category>
		<category><![CDATA[SQL Server Table Size]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1432</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will try to give information about learning the physical size of a table in SQL Server. In SQL Server, in some cases you may want to know the physical size of a table. We use the sp_spaceused procedure for this operation. We run our&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/finding-the-physical-size-of-a-table-in-sql-server">Finding the Physical Size of a Table in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will try to give information about learning the physical size of a table in SQL Server.</p>
<p>In SQL Server, in some cases you may want to know the physical size of a table.</p>
<p>We use the sp_spaceused procedure for this operation.</p>
<p><img decoding="async" class="alignnone wp-image-1434 size-full" src="https://mssqlquery.com/wp-content/uploads/2023/03/finding-the-physical-size-of-a-table-in-sql-server-1.jpg" alt="" width="700" height="446" srcset="https://mssqlquery.com/wp-content/uploads/2023/03/finding-the-physical-size-of-a-table-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2023/03/finding-the-physical-size-of-a-table-in-sql-server-1-300x191.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>We run our procedure by saying exec.</p>
<pre class="line-numbers"><code class="language-sql">EXEC sp_spaceused;</code></pre>
<p>After that, parts such as name information, rows information, and data information of the Products table come.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 49</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/finding-the-physical-size-of-a-table-in-sql-server">Finding the Physical Size of a Table in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>What are the Advantages of Using Procedures in SQL Server?</title>
		<link>https://mssqlquery.com/what-are-the-advantages-of-using-procedures-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Mon, 13 Mar 2023 23:04:42 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[sql server procedure]]></category>
		<category><![CDATA[sql server Procedures]]></category>
		<category><![CDATA[Using Procedures in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1425</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will try to give information about the advantages of using Procedures in SQL Server. Procedures are pre-written code blocks that can be stored and executed in a SQL Server database. Here are some advantages of using procedures in SQL Server: Reusability: Procedures can be&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/what-are-the-advantages-of-using-procedures-in-sql-server">What are the Advantages of Using Procedures in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will try to give information about the advantages of using Procedures in SQL Server.</p>
<p>Procedures are pre-written code blocks that can be stored and executed in a SQL Server database. Here are some advantages of using procedures in SQL Server:</p>
<ol>
<li><strong>Reusability</strong>: Procedures can be reused multiple times, making it an efficient way to execute repetitive tasks. Once a procedure is written, it can be called whenever needed.</li>
<li><strong>Modularity</strong>: Procedures allow you to break down complex logic into smaller, manageable pieces, which makes code maintenance and debugging easier.</li>
<li><strong>Improved Performance</strong>: By using procedures, you can reduce the amount of data that needs to be sent over the network. This can lead to improved performance and reduced network traffic.</li>
<li><strong>Security</strong>: Procedures provide a level of security by allowing you to control access to sensitive data. By granting users permission to execute a procedure rather than directly accessing the data, you can restrict access to the data.</li>
<li><strong>Consistency</strong>: Procedures ensure that database operations are performed consistently. This is particularly important when working with transactions where multiple operations need to be executed together.</li>
<li><strong>Encapsulation</strong>: Procedures can be used to encapsulate business logic, which means that the implementation details are hidden from the user. This makes it easier to modify the implementation without affecting the user interface.</li>
</ol>
<p>Overall, the use of procedures in SQL Server can lead to improved performance, enhanced security, and easier maintenance and development of the database.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 113</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/what-are-the-advantages-of-using-procedures-in-sql-server">What are the Advantages of Using Procedures in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>What Are Commonly Used System Procedures in SQL Server?</title>
		<link>https://mssqlquery.com/what-are-commonly-used-system-procedures-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Fri, 10 Mar 2023 21:21:54 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[System Procedures]]></category>
		<category><![CDATA[System Procedures in SQL Server]]></category>
		<category><![CDATA[What Are Commonly Used System Procedures in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1412</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will try to give information about System Procedures, which are widely used in SQL Server. There are many system procedures available in SQL Server, but some of the commonly used ones are: sp_help: This system procedure provides information about a database object, such as&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/what-are-commonly-used-system-procedures-in-sql-server">What Are Commonly Used System Procedures in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will try to give information about System Procedures, which are widely used in SQL Server.</p>
<p>There are many system procedures available in SQL Server, but some of the commonly used ones are:</p>
<ol>
<li><strong>sp_help</strong>: This system procedure provides information about a database object, such as a table, view, or stored procedure. It can be used to retrieve information about columns, constraints, indexes, and other object properties.</li>
<li><strong>sp_who</strong>: This system procedure displays information about current users and processes connected to the SQL Server instance. It provides details such as the login name, hostname, program name, and status of each process.</li>
<li><strong>sp_configure</strong>: This system procedure is used to view or modify system-level configuration settings in SQL Server. It allows you to change settings such as the maximum amount of memory allocated to SQL Server, network protocols used, and many other options.</li>
<li><strong>sp_spaceused</strong>: This system procedure displays the amount of space used by a table or database in SQL Server. It provides details such as the total size of the table, the amount of space used by indexes, and the amount of space available.</li>
<li><strong>sp_executesql</strong>: This system procedure is used to execute a dynamic SQL statement that is constructed at runtime. It is often used when the exact SQL statement is not known until runtime, such as when building dynamic reports or queries.</li>
<li><strong>sp_rename</strong>: This system procedure is used to rename a database object, such as a table, column, or stored procedure. It can be used to change the name of an object without having to drop and recreate it.</li>
<li><strong>sp_helpindex</strong>: This system procedure provides information about the indexes on a table. It displays the name, type, and columns included in each index, as well as the index size and fragmentation.</li>
</ol>
<p>These are just a few examples of the many system procedures available in SQL Server that can be used for various purposes.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 63</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/what-are-commonly-used-system-procedures-in-sql-server">What Are Commonly Used System Procedures in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Differences Between Stored Procedures and Functions in SQL Server</title>
		<link>https://mssqlquery.com/differences-between-stored-procedures-and-functions-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Sun, 25 Dec 2022 13:16:55 +0000</pubDate>
				<category><![CDATA[Functions]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Differences Between Stored Procedures and Functions in SQL Server]]></category>
		<category><![CDATA[Functions in SQL Server]]></category>
		<category><![CDATA[Stored Procedures and Functions in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1267</guid>

					<description><![CDATA[<p>Hello to everyone, In this article, I will talk about the difference between stored procedures and functions in SQL Server. Stored procedures are sql statements that are stored by the database and do not need to be recompiled after the first compilation. Functions are sql codes that can return any&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/differences-between-stored-procedures-and-functions-in-sql-server">Differences Between Stored Procedures and Functions in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello to everyone,</p>
<p>In this article, I will talk about the difference between stored procedures and functions in SQL Server.</p>
<p>Stored procedures are sql statements that are stored by the database and do not need to be recompiled after the first compilation.</p>
<p>Functions are sql codes that can return any type of value.</p>
<p>The differences between them are below.</p>
<ol>
<li>Functions always return a value (Number, string expression, table, etc.) Stored procedures may or may not return a value.</li>
<li>Functions have only input parameters, but stored procedures have both input and output parameters.</li>
<li>Functions can be run by stored procedures, but stored procedures cannot be run inside functions.</li>
<li>Functions can only be used with a Select statement. CRUD operations are not performed with functions. You can do all CRUD (Create/Read/Update/Delete) operations with stored procedures.</li>
<li>You cannot use the try-catch construct in functions, but you can use it with stored procedures.</li>
<li>Functions do not support transaction structures, but stored procedures do.</li>
<li>Functions do not support the PRINT statement. PRINT statement can be used in stored procedures.</li>
<li>The result set returned by the function can be used in JOIN operations. Not used with stored procedures.</li>
<li>You can use TABLE variable inside the function. Functions The use of TEMPORARY TABLE is not allowed. TABLE variable and TEMPORARY TABLE can be used in stored procedure.</li>
</ol>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 95</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/differences-between-stored-procedures-and-functions-in-sql-server">Differences Between Stored Procedures and Functions in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Viewing Stored Procedure Parameters in Detail in SQL Server</title>
		<link>https://mssqlquery.com/viewing-stored-procedure-parameters-in-detail-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Tue, 28 Jun 2022 17:34:16 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Stored Procedure]]></category>
		<category><![CDATA[Stored Procedure Parameters]]></category>
		<category><![CDATA[Viewing Stored Procedure Parameters]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=1017</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will try to give information about displaying Stored Procedure parameters in SQL Server in detail. In SQL Server, in some cases, you may want to view the Stored Procedure parameters in detail. You can easily do this using the code below. SELECT 'Parameter_name' =&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/viewing-stored-procedure-parameters-in-detail-in-sql-server">Viewing Stored Procedure Parameters in Detail in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will try to give information about displaying Stored Procedure parameters in SQL Server in detail.</p>
<p>In SQL Server, in some cases, you may want to view the Stored Procedure parameters in detail.</p>
<p>You can easily do this using the code below.</p>
<pre class="line-numbers"><code class="language-sql">SELECT 'Parameter_name' = name,
       'Type' = TYPE_NAME(user_type_id),
       'Length' = max_length,
       'Prec' = CASE
                    WHEN TYPE_NAME(system_type_id) = 'uniqueidentifier' THEN
                        precision
                    ELSE
                        OdbcPrec(system_type_id, max_length, precision)
                END,
       'Scale' = OdbcScale(system_type_id, scale),
       'Param_order' = parameter_id,
       'Collation' = CONVERT(   sysname,
                                CASE
                                    WHEN system_type_id IN ( 35, 99, 167, 175, 231, 239 ) THEN
                                        SERVERPROPERTY('collation')
                                END
                            )
FROM sys.parameters
WHERE OBJECT_ID = OBJECT_ID('dbo.CustOrderHist'); --Enter the procedure name here.</code></pre>
<p>When you run the above code, you will see a result similar to the one below.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-1019 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/06/viewing-stored-procedure-parameters-in-detail-in-sql-server-1.jpg" alt="Viewing Stored Procedure Parameters in Detail in SQL Server" width="700" height="389" srcset="https://mssqlquery.com/wp-content/uploads/2022/06/viewing-stored-procedure-parameters-in-detail-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/06/viewing-stored-procedure-parameters-in-detail-in-sql-server-1-300x167.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, we have displayed the Stored Procedure parameters in detail.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 149</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/viewing-stored-procedure-parameters-in-detail-in-sql-server">Viewing Stored Procedure Parameters in Detail in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Seeing Procedure Execution Statistics in SQL Server</title>
		<link>https://mssqlquery.com/seeing-procedure-execution-statistics-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Sat, 21 May 2022 18:35:02 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Execution Statistics in SQL Server]]></category>
		<category><![CDATA[Seeing Procedure Execution Statistics]]></category>
		<category><![CDATA[SQL Server Execution Statistics]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=970</guid>

					<description><![CDATA[<p>Hello to everyone, In this article, I will try to give information about seeing Procedure Execution Statistics in SQL Server. In SQL Server you may want to see Procedure Execution Statistics in some cases. One advantage of Stored Procedures is that performance can be tracked. There may be many Stored&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/seeing-procedure-execution-statistics-in-sql-server">Seeing Procedure Execution Statistics in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello to everyone,</p>
<p>In this article, I will try to give information about seeing Procedure Execution Statistics in SQL Server.</p>
<p>In SQL Server you may want to see Procedure Execution Statistics in some cases.</p>
<p>One advantage of Stored Procedures is that performance can be tracked. There may be many Stored Procedures in our database or SQL Server. You may want to see information such as how long they work, their working time, how much resources they use. This information shows us the information from the last run time of SQL Server to the time of writing the query. This information is kept in Memory and Cache. This information is lost when a restart is performed on SQL Server, but it is easy and useful to log the working information of historical Stored Procedures.</p>
<p>You can easily do this using the code below.</p>
<pre class="line-numbers"><code class="language-sql">SELECT database_id,
       object_id,
       OBJECT_NAME(object_id, database_id) AS 'Prosedür Adı',
       cached_time,
       last_execution_time,
       total_elapsed_time,
       (total_elapsed_time / execution_count) AS 'AVG Elapsed Time',
       last_elapsed_time,
       execution_count
FROM sys.dm_exec_procedure_stats
WHERE database_id = DB_ID('AdventureWorks');</code></pre>
<p>When you run the above code, you will see a result similar to the one below.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-972 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/05/seeing-procedure-execution-statistics-in-sql-server-1.jpg" alt="Seeing Procedure Execution Statistics in SQL Server" width="700" height="388" srcset="https://mssqlquery.com/wp-content/uploads/2022/05/seeing-procedure-execution-statistics-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/05/seeing-procedure-execution-statistics-in-sql-server-1-300x166.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, we have seen the Procedure Execution Statistics.</p>
<p>Stored Procedure name, last run time, time elapsed when the procedure was run, how many times the procedure ran, etc. We were able to access information such as and show it in tabular form.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 194</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/seeing-procedure-execution-statistics-in-sql-server">Seeing Procedure Execution Statistics in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Procedure to Return Previous Week&#8217;s Failed Login List in SQL Server</title>
		<link>https://mssqlquery.com/procedure-to-return-previous-weeks-failed-login-list-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Thu, 31 Mar 2022 08:45:01 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Failed Login List in SQL Server]]></category>
		<category><![CDATA[Previous Week's Failed Login List in SQL Server]]></category>
		<category><![CDATA[Return Previous Week's Failed Login List in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=806</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will provide information about the procedure that brings the previous week&#8217;s list of failed logins in SQL Server. It is also very important for security to track failed login attempts to SQL Server. With the help of the procedure below, you can also track&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/procedure-to-return-previous-weeks-failed-login-list-in-sql-server">Procedure to Return Previous Week’s Failed Login List in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="7">Hello everyone,</span></span></p>
<p><span class="VIiyi" lang="en"> <span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="2" data-number-of-phrases="7">In this article, I will provide information about the procedure that brings the previous week&#8217;s list of failed logins in SQL Server.</span> </span></p>
<p><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="4" data-number-of-phrases="7">It is also very important for security to track failed login attempts to SQL Server.</span> </span></p>
<p><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="6" data-number-of-phrases="7">With the help of the procedure below, you can also track failed logins.</span></span></p>
<pre class="line-numbers"><code class="language-sql">CREATE PROC <span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">sp_PreviousWeekFailedLoginList</span></span> 
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ErrorLogCount INT;
    DECLARE @LastLogDate DATETIME;

    DECLARE @ErrorLogInfo TABLE
    (
        LogDate DATETIME,
        ProcessInfo NVARCHAR(50),
        [Text] NVARCHAR(MAX)
    );

    DECLARE @EnumErrorLogs TABLE
    (
        [Archive#] INT,
        [Date] DATETIME,
        LogFileSizeMB INT
    );

    INSERT INTO @EnumErrorLogs
    EXEC sp_enumerrorlogs;

    SELECT @ErrorLogCount = MIN([Archive#]),
           @LastLogDate = MAX([Date])
    FROM @EnumErrorLogs;

    WHILE @ErrorLogCount IS NOT NULL
    BEGIN

        INSERT INTO @ErrorLogInfo
        EXEC sp_readerrorlog @ErrorLogCount;

        SELECT @ErrorLogCount = MIN([Archive#]),
               @LastLogDate = MAX([Date])
        FROM @EnumErrorLogs
        WHERE [Archive#] &gt; @ErrorLogCount
              AND @LastLogDate &gt; GETDATE() - 1;

    END;

    SELECT COUNT(Text) AS NumberOfAttempts,
           Text AS Details,
           MIN(LogDate) AS MinLogDate,
           MAX(LogDate) AS MaxLogDate
    FROM @ErrorLogInfo
    WHERE ProcessInfo = 'Logon'
          AND Text LIKE '%fail%'
          AND LogDate &gt; GETDATE() - 1
    GROUP BY Text
    ORDER BY NumberOfAttempts DESC;

    SET NOCOUNT OFF;
END;


--<span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Use of</span></span> Procedure

EXEC <span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">sp_PreviousWeekFailedLoginList</span></span> ;</code></pre>
<p><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Good luck to everyone in business and life.</span></span></p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 259</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/procedure-to-return-previous-weeks-failed-login-list-in-sql-server">Procedure to Return Previous Week’s Failed Login List in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Data Compression Procedure for All Tables in SQL Server</title>
		<link>https://mssqlquery.com/data-compression-procedure-for-all-tables-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Tue, 29 Mar 2022 17:13:24 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Data Compression]]></category>
		<category><![CDATA[Data Compression Procedure]]></category>
		<category><![CDATA[Data Compression Procedure for All Tables]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=802</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will give information about data compression procedure for all tables in SQL Server. There are two types of data compression. Row Level Data Compression: A compression method that converts fixed-length data types to variable-length data types and frees up free space. It also saves&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/data-compression-procedure-for-all-tables-in-sql-server">Data Compression Procedure for All Tables in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will give information about data compression procedure for all tables in SQL Server.</p>
<p>There are two types of data compression.</p>
<p><strong>Row Level Data Compression:</strong> A compression method that converts fixed-length data types to variable-length data types and frees up free space. It also saves additional space by ignoring zero and null values. In contrast, it can fit more rows in a single data sheet.</p>
<p><strong>Page-Level Data Compression:</strong> A compression method that starts with row-level data compression and then adds a prefix and a dictionary compression for data pages.</p>
<p>The following procedure expects either <strong>ROW</strong> or <strong>PAGE</strong> parameter. Which compression type you want to use, you can run that parameter by writing it to the procedure.</p>
<pre class="line-numbers"><code class="language-sql">CREATE PROCEDURE DataCompressionProcedureforAllTables 
(@compression_method CHAR(4))
AS
SET NOCOUNT ON;
BEGIN
    DECLARE @schema_name sysname,
            @table_name sysname;
    CREATE TABLE #compress_report_tb
    (
        ObjName sysname,
        schemaName sysname,
        indx_ID INT,
        partit_number INT,
        size_with_current_compression_setting BIGINT,
        size_with_requested_compression_setting BIGINT,
        sample_size_with_current_compression_setting BIGINT,
        sample_size_with_requested_compression_setting BIGINT
    );
    DECLARE c_sch_tb_crs CURSOR FOR
    SELECT TABLE_SCHEMA,
           TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE LIKE 'BASE%'
          AND TABLE_CATALOG = UPPER(DB_NAME());
    OPEN c_sch_tb_crs;
    FETCH NEXT FROM c_sch_tb_crs
    INTO @schema_name,
         @table_name;
    WHILE @@Fetch_Status = 0
    BEGIN
        INSERT INTO #compress_report_tb
        EXEC sp_estimate_data_compression_savings @schema_name = @schema_name,
                                                  @object_name = @table_name,
                                                  @index_id = NULL,
                                                  @partition_number = NULL,
                                                  @data_compression = @compression_method;
        FETCH NEXT FROM c_sch_tb_crs
        INTO @schema_name,
             @table_name;
    END;
    CLOSE c_sch_tb_crs;
    DEALLOCATE c_sch_tb_crs;
    SELECT schemaName AS [schema_name],
           ObjName AS [table_name],
           AVG(size_with_current_compression_setting) AS avg_size_with_current_compression_setting,
           AVG(size_with_requested_compression_setting) AS avg_size_with_requested_compression_setting,
           AVG(size_with_current_compression_setting - size_with_requested_compression_setting) AS avg_size_saving
    FROM #compress_report_tb
    GROUP BY schemaName,
             ObjName
    ORDER BY schemaName ASC,
             avg_size_saving DESC;
    DROP TABLE #compress_report_tb;
END;
SET NOCOUNT OFF;


--Usage 
--Run after selecting the relevant database. Otherwise, the responsibility belongs to you.

EXEC DataCompressionProcedureforAllTables @compression_method= 'PAGE';
GO</code></pre>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 146</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/data-compression-procedure-for-all-tables-in-sql-server">Data Compression Procedure for All Tables in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Removing All Procedures in SQL Server</title>
		<link>https://mssqlquery.com/removing-all-procedures-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Sun, 13 Mar 2022 00:16:37 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[all procedure remove]]></category>
		<category><![CDATA[drop all procedures]]></category>
		<category><![CDATA[Removing All Procedures in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=786</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will provide information on how to remove all procedures in SQL Server. In SQL Server we may want to remove all procedures in some cases. You can easily do this using the code below. DECLARE @procName VARCHAR(500); DECLARE cur CURSOR FOR SELECT [name] FROM&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/removing-all-procedures-in-sql-server">Removing All Procedures in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will provide information on how to remove all procedures in SQL Server.</p>
<p>In SQL Server we may want to remove all procedures in some cases.</p>
<p>You can easily do this using the code below.</p>
<pre class="line-numbers"><code class="language-sql">DECLARE @procName VARCHAR(500);
DECLARE cur CURSOR FOR SELECT [name] FROM sys.objects WHERE type = 'p';
OPEN cur;
FETCH NEXT FROM cur
INTO @procName;
WHILE @@fetch_status = 0
BEGIN
    EXEC ('drop procedure [' + @procName + ']');
    FETCH NEXT FROM cur
    INTO @procName;
END;
CLOSE cur;
DEALLOCATE cur;</code></pre>
<p>When you run the above code, all procedures in the relevant database will be removed.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 139</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/removing-all-procedures-in-sql-server">Removing All Procedures in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>What are the Differences Between Function and Procedure in SQL Server?</title>
		<link>https://mssqlquery.com/what-are-the-differences-between-function-and-procedure-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Fri, 11 Mar 2022 20:12:36 +0000</pubDate>
				<category><![CDATA[Functions]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Differences Between Function and Procedure]]></category>
		<category><![CDATA[Function and Procedure]]></category>
		<category><![CDATA[Function and Procedure in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=777</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will give information about what are the Differences Between Function and Procedure in SQL Server. This question especially comes to mind of curious friends who are just learning SQL Server. This question may come up in job interviews. It is useful to know briefly,&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/what-are-the-differences-between-function-and-procedure-in-sql-server">What are the Differences Between Function and Procedure in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will give information about what are the Differences Between Function and Procedure in SQL Server.</p>
<p>This question especially comes to mind of curious friends who are just learning SQL Server. This question may come up in job interviews. It is useful to know briefly, because in the programming world, it is more important to do something efficiently and with less resources than to do it.</p>
<ol>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="2">The function must always return a value.</span> <span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="1" data-number-of-phrases="2">(Number, text, table etc.) but Stored Procedure is optional, it may not have a return value.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="2">You cannot use a try-catch construct in a function.</span> <span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="1" data-number-of-phrases="2">You can use it in Stored Procedure.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Function can only be used with Select, it doesn&#8217;t update or delete, Stored Procedure can do all CRUD(CREATE/READ/UPDATE/DELETE) operations.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Function has only input parameters, but Stored Procedures can use both input and output parameters.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Function can be called by Stored Procedure but Stored Procedure cannot be called by Function.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Functions do not support Transaction constructs, but Stored Procedures do.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="2">Only variable table values can be used in functions, Temporary tables cannot be used.</span> <span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="1" data-number-of-phrases="2">You can use both in procedures.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Functions can be used anywhere in the WHERE/HAVING/SELECT section, while Stored Procedures cannot.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Functions can be called and used using Select and Stored Procedures using Exec or Execute.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">We cannot use indexes in functions, they can be used in Stored Procedures.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">Trigger is not used in Functions, it can be used in Stored Procedure.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">While functions are not compiled once, Stored Procedures are compiled once and work efficiently.</span></span></li>
<li><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="1">It can be used in functions with Join structure, not in Stored Procedures.</span></span></li>
</ol>
<p><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="0" data-number-of-phrases="3">I hope it was useful.</span> </span></p>
<p><span class="VIiyi" lang="en"><span class="JLqJ4b ChMk0b" data-language-for-alternatives="en" data-language-to-translate-into="tr" data-phrase-index="2" data-number-of-phrases="3">Good luck to everyone in business and life.</span></span></p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 150</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/what-are-the-differences-between-function-and-procedure-in-sql-server">What are the Differences Between Function and Procedure in SQL Server?</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Finding Last Used Stored Procedure in SQL Server</title>
		<link>https://mssqlquery.com/finding-last-used-stored-procedure-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Tue, 01 Mar 2022 16:36:14 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Finding Last Used Stored Procedure]]></category>
		<category><![CDATA[SQL Server Last Used Procedure]]></category>
		<category><![CDATA[Stored Procedure in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=738</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will try to give information about finding the last used Stored Procedure in SQL Server. In SQL Server in some cases you may want to find the last used Stored Procedure. You can easily do this using the script below. SELECT DB_NAME(qt.[dbid]) AS [DatabaseName],&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/finding-last-used-stored-procedure-in-sql-server">Finding Last Used Stored Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will try to give information about finding the last used Stored Procedure in SQL Server.</p>
<p>In SQL Server in some cases you may want to find the last used Stored Procedure.</p>
<p>You can easily do this using the script below.</p>
<pre class="line-numbers"><code class="language-sql">SELECT DB_NAME(qt.[dbid]) AS [DatabaseName],
       OBJECT_NAME(qt.[objectid], qt.[dbid]) AS [SP Name],
       qs.execution_count AS [Execution Count],
       qs.max_logical_reads,
       qs.max_logical_writes,
       qs.creation_time,
       DATEDIFF(MINUTE, qs.creation_time, GETDATE()) AS [Age in Cache]
FROM sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.[sql_handle]) AS qt
WHERE LEN(OBJECT_NAME(qt.[objectid], qt.[dbid])) &gt; 0
ORDER BY DB_NAME(qt.[dbid]) DESC,
         OBJECT_NAME(qt.[objectid], qt.[dbid]) DESC;</code></pre>
<p>When you run the above code, you will see a result similar to the one below.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-741 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/02/finding-last-used-stored-procedure-in-sql-server-1.jpg" alt="Finding Last Used Stored Procedure in SQL Server" width="700" height="473" srcset="https://mssqlquery.com/wp-content/uploads/2022/02/finding-last-used-stored-procedure-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/02/finding-last-used-stored-procedure-in-sql-server-1-300x203.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, we have found the Stored Procedure we used last time.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 171</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/finding-last-used-stored-procedure-in-sql-server">Finding Last Used Stored Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Listing Disk Spaces in SQL Server</title>
		<link>https://mssqlquery.com/listing-disk-spaces-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Sat, 26 Feb 2022 13:27:48 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Listing Disk Spaces SQL]]></category>
		<category><![CDATA[SQL Server Disk Space]]></category>
		<category><![CDATA[TSQL Disk Space]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=712</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will talk about how to list disk spaces in SQL Server. In SQL Server, in some cases, it may be desired to display disk spaces with a query. In such cases, we can list the disk spaces using the following query. EXEC master..xp_fixeddrives; When&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/listing-disk-spaces-in-sql-server">Listing Disk Spaces in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will talk about how to list disk spaces in SQL Server.</p>
<p>In SQL Server, in some cases, it may be desired to display disk spaces with a query.</p>
<p>In such cases, we can list the disk spaces using the following query.</p>
<pre class="line-numbers"><code class="language-sql">EXEC master..xp_fixeddrives;</code></pre>
<p>When we run the relevant query, we will get a result as follows.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-715 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/02/listing-disk-spaces-in-sql-server-1.jpg" alt="Listing Disk Spaces in SQL Server" width="700" height="367" srcset="https://mssqlquery.com/wp-content/uploads/2022/02/listing-disk-spaces-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/02/listing-disk-spaces-in-sql-server-1-300x157.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, the disk spaces are listed.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 161</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/listing-disk-spaces-in-sql-server">Listing Disk Spaces in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Generating the Code to Remove All Procedures in SQL Server</title>
		<link>https://mssqlquery.com/generating-the-code-to-remove-all-procedures-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Tue, 22 Feb 2022 17:31:59 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Generating the Code]]></category>
		<category><![CDATA[Generating the Code to Remove All Procedures]]></category>
		<category><![CDATA[Remove All Procedures in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=672</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will talk about how to dynamically generate code for removing all procedures in SQL Server. In SQL Server, in some cases, instead of removing the procedures by manually writing the code, we can remove the relevant procedures by dynamically generating code. You can see&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/generating-the-code-to-remove-all-procedures-in-sql-server">Generating the Code to Remove All Procedures in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will talk about how to dynamically generate code for removing all procedures in SQL Server.</p>
<p>In SQL Server, in some cases, instead of removing the procedures by manually writing the code, we can remove the relevant procedures by dynamically generating code.</p>
<p>You can see the relevant code below.</p>
<pre class="line-numbers"><code class="language-sql">SELECT 'DROP PROC ' + '[' + ROUTINE_SCHEMA + ']' + '.' + '[' + ROUTINE_NAME + ']'
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE';</code></pre>
<p>When we run the relevant code on the Northwind database, you will see the following result.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-674 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/02/generating-the-code-to-remove-all-procedures-in-sql-server-1.jpg" alt="Generating the Code to Remove All Procedures in SQL Server" width="700" height="419" srcset="https://mssqlquery.com/wp-content/uploads/2022/02/generating-the-code-to-remove-all-procedures-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/02/generating-the-code-to-remove-all-procedures-in-sql-server-1-300x180.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, the following codes were generated.</p>
<pre class="line-numbers"><code class="language-sql">DROP PROC [dbo].[Ten Most Expensive Products];
DROP PROC [dbo].[Employee Sales by Country];
DROP PROC [dbo].[Sales by Year];
DROP PROC [dbo].[CustOrdersDetail];
DROP PROC [dbo].[CustOrdersOrders];
DROP PROC [dbo].[CustOrderHist];
DROP PROC [dbo].[SalesByCategory];
DROP PROC [dbo].[sp_upgraddiagrams];
DROP PROC [dbo].[sp_helpdiagrams];
DROP PROC [dbo].[sp_helpdiagramdefinition];
DROP PROC [dbo].[sp_creatediagram];
DROP PROC [dbo].[sp_renamediagram];
DROP PROC [dbo].[sp_alterdiagram];
DROP PROC [dbo].[sp_dropdiagram];
DROP PROC [dbo].[ScriptCreateTableKeys];
DROP PROC [dbo].[ScriptCreateTableKeys2];</code></pre>
<p>You can run whatever you want according to your needs, or you can run them all together and remove all procedures.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 132</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/generating-the-code-to-remove-all-procedures-in-sql-server">Generating the Code to Remove All Procedures in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Scripting Table Key Fields in SQL Server</title>
		<link>https://mssqlquery.com/scripting-table-key-fields-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Sun, 20 Feb 2022 12:28:03 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Scripting Table Key Fields]]></category>
		<category><![CDATA[Scripting Table SQL]]></category>
		<category><![CDATA[Table Key Fields in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=642</guid>

					<description><![CDATA[<p>The process we will do is to create the script of the key fields of a table, namely the Primary Key, Foreign Key and Index Key fields. Even though I don&#8217;t use it much, in SQL Server, in some cases, we may only need to create a script for the&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/scripting-table-key-fields-in-sql-server">Scripting Table Key Fields in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>The process we will do is to create the script of the key fields of a table, namely the Primary Key, Foreign Key and Index Key fields.</p>
<p>Even though I don&#8217;t use it much, in SQL Server, in some cases, we may only need to create a script for the key fields. In addition, I think that this process, which we will do on a table basis, will save us from code confusion. It can also be useful if something like a backup of table-based key fields is to be made.</p>
<p>First of all, you should create the following procedure in your related database. I created the following procedure in Adventureworks database as an example.</p>
<pre class="line-numbers"><code class="language-sql">CREATE PROC [dbo].[TabloKeylerininScriptiniAl] @table_name sysname
AS
BEGIN

    SET NOCOUNT ON;


    DECLARE @crlf CHAR(2);

    SET @crlf = CHAR(13) + CHAR(10);

    DECLARE @version CHAR(4);

    SET @version = SUBSTRING(@@VERSION, LEN('Microsoft SQL Server') + 2, 4);

    DECLARE @object_id INT;

    SET @object_id = OBJECT_ID(@table_name);

    DECLARE @sql NVARCHAR(MAX);



    /*    IF @version NOT IN ( '2005', '2008' )
    BEGIN

        RAISERROR('This script only supports SQL Server 2005 and 2008', 16, 1);

        RETURN;

    END;*/



    SET @sql
        = N'' + N'SELECT ' + N'CASE ' + N'WHEN 1 IN (i.is_primary_key, i.is_unique_constraint) THEN '
          + N'''ALTER TABLE '' + ' + N'QUOTENAME(OBJECT_SCHEMA_NAME(i.object_id)) + ''.'' + '
          + N'QUOTENAME(OBJECT_NAME(i.object_id)) + @crlf + ' + N'''ADD '' + ' + N'CASE k.is_system_named '
          + N'WHEN 0 THEN ''CONSTRAINT '' + QUOTENAME(k.name) + @crlf ' + N'ELSE '''' ' + N'END + ' + N'CASE k.type '
          + N'WHEN ''UQ'' THEN ''UNIQUE'' ' + N'ELSE ''PRIMARY KEY'' ' + N'END + '' '' + ' + N'i.type_desc  + @crlf + '
          + N'kc.key_columns + @crlf ' + N'ELSE ' + N'''CREATE UNIQUE '' + i.type_desc + '' INDEX '' + '
          + N'QUOTENAME(i.name) + @crlf + ' + N'''ON '' + ' + N'QUOTENAME(OBJECT_SCHEMA_NAME(i.object_id)) + ''.'' + '
          + N'QUOTENAME(OBJECT_NAME(i.object_id)) + @crlf + ' + N'kc.key_columns + @crlf + ' + N'COALESCE ' + N'( '
          + N'''INCLUDE '' + @crlf + ' + N'''( '' + @crlf + ' + N'STUFF ' + N'( ' + N'( ' + N'SELECT ' + N'( '
          + N'SELECT ' + N''','' + @crlf + '' '' + QUOTENAME(c.name) AS [text()] ' + N'FROM sys.index_columns AS ic '
          + N'JOIN sys.columns AS c ON ' + N'c.object_id = ic.object_id ' + N'AND c.column_id = ic.column_id '
          + N'WHERE ' + N'ic.object_id = i.object_id ' + N'AND ic.index_id = i.index_id '
          + N'AND ic.is_included_column = 1 ' + N'ORDER BY ' + N'ic.key_ordinal ' + N'FOR XML PATH(''''), TYPE '
          + N').value(''.'', ''VARCHAR(MAX)'') ' + N'), ' + N'1, ' + N'3, ' + N''''' ' + N') + @crlf + '
          + N''')'' + @crlf, ' + N''''' ' + N') ' + N'END + ' + N'''WITH '' + @crlf + ' + N'''('' + @crlf + '
          + N''' PAD_INDEX = '' + ' + N'CASE CONVERT(VARCHAR, i.is_padded) ' + N'WHEN 1 THEN ''ON'' '
          + N'ELSE ''OFF'' ' + N'END + '','' + @crlf + ' + N'CASE i.fill_factor ' + N'WHEN 0 THEN '''' ' + N'ELSE '
          + N''' FILLFACTOR = '' + ' + N'CONVERT(VARCHAR, i.fill_factor) + '','' + @crlf ' + N'END + '
          + N''' IGNORE_DUP_KEY = '' + ' + N'CASE CONVERT(VARCHAR, i.ignore_dup_key) ' + N'WHEN 1 THEN ''ON'' '
          + N'ELSE ''OFF'' ' + N'END + '','' + @crlf + ' + N''' ALLOW_ROW_LOCKS = '' + '
          + N'CASE CONVERT(VARCHAR, i.allow_row_locks) ' + N'WHEN 1 THEN ''ON'' ' + N'ELSE ''OFF'' '
          + N'END + '','' + @crlf + ' + N''' ALLOW_PAGE_LOCKS = '' + ' + N'CASE CONVERT(VARCHAR, i.allow_page_locks) '
          + N'WHEN 1 THEN ''ON'' ' + N'ELSE ''OFF'' ' + N'END + '
          + CASE @version
                WHEN '2005' THEN
                    ''
                ELSE
                    ''','' + @crlf + ' + ''' DATA_COMPRESSION = '' + ' + '( ' + 'SELECT ' + 'CASE '
                    + 'WHEN MIN(p.data_compression_desc) =

                                          MAX(p.data_compression_desc)

                                          THEN MAX(p.data_compression_desc) '
                    + 'ELSE ''[PARTITIONS USE

                                          MULTIPLE COMPRESSION TYPES]'' '
                    + 'END ' + 'FROM sys.partitions AS p ' + 'WHERE ' + 'p.object_id = i.object_id '
                    + 'AND p.index_id = i.index_id ' + ') '
            END + N'+ @crlf + ' + N''') '' + @crlf + ' + N'''ON '' + ds.data_space + '';'' + '
          + N'@crlf + @crlf COLLATE database_default AS [-- Create Candidate Keys] ' + N'FROM sys.indexes AS i '
          + N'LEFT OUTER JOIN sys.key_constraints AS k ON ' + N'k.parent_object_id = i.object_id '
          + N'AND k.unique_index_id = i.index_id ' + N'CROSS APPLY ' + N'( ' + N'SELECT ' + N'''( '' + @crlf + '
          + N'STUFF ' + N'( ' + N'( ' + N'SELECT ' + N'( ' + N'SELECT '
          + N''','' + @crlf + '' '' + QUOTENAME(c.name) AS [text()] ' + N'FROM sys.index_columns AS ic '
          + N'JOIN sys.columns AS c ON ' + N'c.object_id = ic.object_id ' + N'AND c.column_id = ic.column_id '
          + N'WHERE ' + N'ic.object_id = i.object_id ' + N'AND ic.index_id = i.index_id ' + N'AND ic.key_ordinal &gt; 0 '
          + N'ORDER BY ' + N'ic.key_ordinal ' + N'FOR XML PATH(''''), TYPE ' + N').value(''.'', ''VARCHAR(MAX)'') '
          + N'), ' + N'1, ' + N'3, ' + N''''' ' + N') + @crlf + ' + N''')'' ' + N') AS kc (key_columns) '
          + N'CROSS APPLY ' + N'( ' + N'SELECT ' + N'QUOTENAME(d.name) + ' + N'CASE d.type ' + N'WHEN ''PS'' THEN '
          + N'+ ' + N'''('' + ' + N'( ' + N'SELECT ' + N'QUOTENAME(c.name) ' + N'FROM sys.index_columns AS ic '
          + N'JOIN sys.columns AS c ON ' + N'c.object_id = ic.object_id ' + N'AND c.column_id = ic.column_id '
          + N'WHERE ' + N'ic.object_id = i.object_id ' + N'AND ic.index_id = i.index_id '
          + N'AND ic.partition_ordinal = 1 ' + N') + ' + N''')'' ' + N'ELSE '''' ' + N'END '
          + N'FROM sys.data_spaces AS d ' + N'WHERE ' + N'd.data_space_id = i.data_space_id '
          + N') AS ds (data_space) ' + N'WHERE ' + N'i.object_id = @object_id ' + N'AND i.is_unique = 1 ' +

    --filtered and hypothetical indexes cannot be candidate keys

    CASE @version
        WHEN '2008' THEN
            'AND i.has_filter = 0 '
        ELSE
            ''
    END        + N'AND i.is_hypothetical = 0 ' + N'AND i.is_disabled = 0 ' + N'ORDER BY ' + N'i.index_id ';



    EXEC sp_executesql @sql,
                       N'@object_id INT, @crlf CHAR(2)',
                       @object_id,
                       @crlf;



    SELECT 'ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(fk.parent_object_id)) + '.'
           + QUOTENAME(OBJECT_NAME(fk.parent_object_id)) + @crlf + CASE fk.is_not_trusted
                                                                       WHEN 0 THEN
                                                                           'WITH CHECK '
                                                                       ELSE
                                                                           'WITH NOCHECK '
                                                                   END + 'ADD '
           + CASE fk.is_system_named
                 WHEN 0 THEN
                     'CONSTRAINT ' + QUOTENAME(name) + @crlf
                 ELSE
                     ''
             END + 'FOREIGN KEY ' + @crlf + '( ' + @crlf
           + STUFF(
             (
                 SELECT
                     (
                         SELECT ',' + @crlf + ' ' + QUOTENAME(c.name) AS [text()]
                         FROM sys.foreign_key_columns AS fc
                             JOIN sys.columns AS c
                                 ON c.object_id = fc.parent_object_id
                                    AND c.column_id = fc.parent_column_id
                         WHERE fc.constraint_object_id = fk.object_id
                         ORDER BY fc.constraint_column_id
                         FOR XML PATH(''), TYPE
                     ).value('.', 'VARCHAR(MAX)')
             ),
             1,
             3,
             ''
                  ) + @crlf + ') ' + 'REFERENCES ' + QUOTENAME(OBJECT_SCHEMA_NAME(fk.referenced_object_id)) + '.'
           + QUOTENAME(OBJECT_NAME(fk.referenced_object_id)) + @crlf + '( ' + @crlf
           + STUFF(
             (
                 SELECT
                     (
                         SELECT ',' + @crlf + ' ' + QUOTENAME(c.name) AS [text()]
                         FROM sys.foreign_key_columns AS fc
                             JOIN sys.columns AS c
                                 ON c.object_id = fc.referenced_object_id
                                    AND c.column_id = fc.referenced_column_id
                         WHERE fc.constraint_object_id = fk.object_id
                         ORDER BY fc.constraint_column_id
                         FOR XML PATH(''), TYPE
                     ).value('.', 'VARCHAR(MAX)')
             ),
             1,
             3,
             ''
                  ) + @crlf + ');' + @crlf + @crlf COLLATE DATABASE_DEFAULT AS [-- Create Referencing FKs]
    FROM sys.foreign_keys AS fk
    WHERE referenced_object_id = @object_id
          AND is_disabled = 0
    ORDER BY key_index_id;



END;


--Kullanımı

EXEC [dbo].[TabloKeylerininScriptiniAl] @table_name = 'Production.Product';</code></pre>
<p>After creating the procedure, let&#8217;s run it.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-645 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/02/scripting-table-key-fields-in-sql-server-1.jpg" alt="Scripting Table Key Fields in SQL Server" width="700" height="402" srcset="https://mssqlquery.com/wp-content/uploads/2022/02/scripting-table-key-fields-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/02/scripting-table-key-fields-in-sql-server-1-300x172.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, the script of the Primary Key, Foreign Key and Index Key fields has been created.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 193</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/scripting-table-key-fields-in-sql-server">Scripting Table Key Fields in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Searching for Words in All Tables in SQL Server</title>
		<link>https://mssqlquery.com/searching-for-words-in-all-tables-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Thu, 17 Feb 2022 18:40:59 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[All Tables in SQL Server]]></category>
		<category><![CDATA[All Tables Search in SQL Server]]></category>
		<category><![CDATA[Searching for Words in All Tables in SQL Server]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=634</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will try to share information about searching words in all tables in SQL Server. In SQL Server, in some cases, we may want to find a word we want in all tables. You can easily do this using the procedure below. Note: It may&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/searching-for-words-in-all-tables-in-sql-server">Searching for Words in All Tables in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will try to share information about searching words in all tables in SQL Server.</p>
<p>In SQL Server, in some cases, we may want to find a word we want in all tables.</p>
<p>You can easily do this using the procedure below.</p>
<p><strong>Note:</strong> It may cause performance problems in tables with a large number of records or tables. You can use it in Small and Medium databases.</p>
<pre class="line-numbers"><code class="language-sql">CREATE   PROC SearchingforWordsinAllTables
(@WordToSearch NVARCHAR(100))
AS
BEGIN

    CREATE TABLE #Sonuc
    (
        ColumnName NVARCHAR(370),
        ColumnValue NVARCHAR(3630)
    );

    SET NOCOUNT ON;

    DECLARE @TableName NVARCHAR(256),
            @ColumnName NVARCHAR(128),
            @Word NVARCHAR(110);

    SET @TableName = N'';
    SET @Word = QUOTENAME('%' + @WordToSearch + '%', '''');

    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = N'';
        SET @TableName =
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_TYPE = 'BASE TABLE'
                  AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) &gt; @TableName
                  AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
        );

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
                      AND TABLE_NAME = PARSENAME(@TableName, 1)
                      AND DATA_TYPE IN ( 'char', 'varchar', 'nchar', 'nvarchar','ntext' )
                      AND QUOTENAME(COLUMN_NAME) &gt; @ColumnName
            );
            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO #Sonuc
                EXEC ('SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(CAST(' + @ColumnName + 'as varchar(max)), 3630) FROM ' + @TableName + ' (NOLOCK) ' + ' WHERE ' + @ColumnName + ' LIKE ' + @Word);
            END;
        END;
    END;

    SELECT ColumnName,
           ColumnValue
    FROM #Sonuc;

END;

--Use of Procedure

EXEC SearchingforWordsinAllTables  'Dried fruit and bean curd';</code></pre>
<p>&nbsp;</p>
<p>Let&#8217;s create the procedure and test it.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-635 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/02/searching-for-words-in-all-tables-in-sql-server-1.jpg" alt="Searching for Words in All Tables in SQL Server" width="700" height="396" srcset="https://mssqlquery.com/wp-content/uploads/2022/02/searching-for-words-in-all-tables-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/02/searching-for-words-in-all-tables-in-sql-server-1-300x170.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>When you run the procedure, you will see a result like the one above.</p>
<p>The procedure searches &#8216;CHAR&#8217;, &#8216;VARCHAR&#8217;, &#8216;NCHAR&#8217;, &#8216;NVARCHAR&#8217;, &#8216;NTEXT&#8217; fields.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 258</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/searching-for-words-in-all-tables-in-sql-server">Searching for Words in All Tables in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Prime Number Checking Procedure in SQL Server</title>
		<link>https://mssqlquery.com/prime-number-checking-procedure-in-sql-server</link>
		
		<dc:creator><![CDATA[Yavuz Selim Kart]]></dc:creator>
		<pubDate>Tue, 18 Jan 2022 18:04:02 +0000</pubDate>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[SQL Server Prime Number Control]]></category>
		<category><![CDATA[SQL Server Prime Number Procedure]]></category>
		<category><![CDATA[TSQL Prime Number]]></category>
		<guid isPermaLink="false">https://mssqlquery.com/?p=529</guid>

					<description><![CDATA[<p>Hello everyone, In this article, I will give information about the prime number checking procedure in SQL Server. You can constantly improve yourself by making such examples in SQL Server. You can easily do this with the help of the code below. CREATE PROC IsNumberPrime @Number INT AS DECLARE @Counter&#46;&#46;&#46;</p>
<p>The post <a href="https://mssqlquery.com/prime-number-checking-procedure-in-sql-server">Prime Number Checking Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>In this article, I will give information about the prime number checking procedure in SQL Server.</p>
<p>You can constantly improve yourself by making such examples in SQL Server.</p>
<p>You can easily do this with the help of the code below.</p>
<pre class="line-numbers"><code class="language-sql">CREATE PROC IsNumberPrime @Number INT
AS
DECLARE @Counter INT;
SET @Counter = 2;
BEGIN
    WHILE (@Counter) &lt; @Number
    BEGIN
        IF (@Number % @Counter = 0)
        BEGIN
            SELECT 'Not Prime';
            RETURN;
        END;
        SET @Counter = @Counter + 1;
    END;
    SELECT 'Prime';
    RETURN;
END;

--Kullanımı 

EXEC dbo.IsNumberPrime @Number = 20;
EXEC dbo.IsNumberPrime @Number = 23;</code></pre>
<p>&nbsp;</p>
<p>When you create the procedure and run the code, you will get a result like the one below.</p>
<p><img decoding="async" loading="lazy" class="alignnone wp-image-531 size-full" src="https://mssqlquery.com/wp-content/uploads/2022/01/prime-number-checking-procedure-in-sql-server-1.jpg" alt="Prime Number Checking Procedure in SQL Server" width="700" height="563" srcset="https://mssqlquery.com/wp-content/uploads/2022/01/prime-number-checking-procedure-in-sql-server-1.jpg 700w, https://mssqlquery.com/wp-content/uploads/2022/01/prime-number-checking-procedure-in-sql-server-1-300x241.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></p>
<p>As you can see, the prime number checking procedure has been created.</p>
<p>Good luck to everyone in business and life.</p>
<div class='epvc-post-count'><span class='epvc-eye'></span>  <span class="epvc-count"> 173</span><span class='epvc-label'> Views</span></div><p>The post <a href="https://mssqlquery.com/prime-number-checking-procedure-in-sql-server">Prime Number Checking Procedure in SQL Server</a> first appeared on <a href="https://mssqlquery.com">MSSQL Query</a>.</p>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
