<?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>sql &#8211; achraf ben alaya</title>
	<atom:link href="https://achrafbenalaya.com/category/blog/sql/feed/" rel="self" type="application/rss+xml" />
	<link>https://achrafbenalaya.com</link>
	<description>Tech Blog By Achraf Ben Alaya</description>
	<lastBuildDate>Sun, 07 Nov 2021 11:38:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.5</generator>

<image>
	<url>/wp-content/uploads/2022/02/cropped-me-scaled-1-32x32.jpeg</url>
	<title>sql &#8211; achraf ben alaya</title>
	<link>https://achrafbenalaya.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">189072172</site>	<item>
		<title>Tools I use with Database</title>
		<link>https://achrafbenalaya.com/2021/11/07/tools-i-use-with-database/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=tools-i-use-with-database</link>
					<comments>https://achrafbenalaya.com/2021/11/07/tools-i-use-with-database/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Sun, 07 Nov 2021 11:38:33 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[Tricks, Tips and Fixes]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=1371</guid>

					<description><![CDATA[If you work a lot with  database/tables and you start working on a project that is ongoing and there is already a tons of tables that exists you may get wasted. In all the projects I worked on I have used SQL server, recently I worked on a project that uses Postgresql, and there was [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>If you work a lot with  database/tables and you start working on a project that is ongoing and there is already a tons of tables that exists you may get wasted.<br />
<img decoding="async" class="aligncenter" src="https://c.tenor.com/jlHAbfAnlVkAAAAC/get-the-tables-dudley-boys.gif" alt="D Von Get The Tables GIFs | Tenor" /></p>
<p>In all the projects I worked on I have used SQL server, recently I worked on a project that uses Postgresql, and there was like a thousand table and I&#8217;m completely lost trying out to understand the schema, the relation between the tables, and where I can find my data, it was really exhausting figuring out the relation between certain tables and for that, I was looking for a tool that can help me/us and there were a few suggestions by the team members that I wanted to share with you.</p>
<h2>Pgadmin :</h2>
<p>&nbsp;</p>
<p>PGAdmin is a web-based GUI tool <b>used to interact with the Postgres database sessions</b>, both locally and remote servers as well. You can use PGAdmin to perform any sort of database administration required for a Postgres database.</p>
<p><img decoding="async" src="https://www.dsfc.net/wp-content/uploads/2017/09/pgadmin-4-dashboard.jpg" alt="Baisser l&amp;#39;impact de l&amp;#39;utilisation de PgAdmin 4 sur PostgreSQL" /></p>
<h2>Azure Data Studio</h2>
<p>Azure Data Studio is <b>a cross-platform database tool for data professionals using on-premises and cloud data platforms</b> on Windows, macOS, and Linux. Azure Data Studio offers a modern editor experience with IntelliSense, code snippets, source control integration, and an integrated terminal.</p>
<h2><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/aztablest.png"><img fetchpriority="high" decoding="async" class="aligncenter size-full wp-image-1373" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/aztablest.png" alt="" width="1316" height="672" srcset="/wp-content/uploads/2021/11/aztablest.png 1316w, /wp-content/uploads/2021/11/aztablest-300x153.png 300w, /wp-content/uploads/2021/11/aztablest-1024x523.png 1024w, /wp-content/uploads/2021/11/aztablest-768x392.png 768w, /wp-content/uploads/2021/11/aztablest-750x383.png 750w, /wp-content/uploads/2021/11/aztablest-1140x582.png 1140w" sizes="(max-width: 1316px) 100vw, 1316px" /></a>DBeaver</h2>
<p>DBeaver is a <b>free, open source multiplatform database management tool and SQL client for developers and database administrators</b>. DBeaver can be used to access any database or cloud application that has an ODBC or JDBC driver, such as Oracle, SQL Server, MySQl, Salesforce, or MailChimp.</p>
<p>For me , this is the most awesome tool to connect and see your tables and  diagrams and let me show you why :</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/dbeaver.png"><img decoding="async" class="aligncenter size-full wp-image-1374" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/dbeaver.png" alt="" width="1892" height="1054" srcset="/wp-content/uploads/2021/11/dbeaver.png 1892w, /wp-content/uploads/2021/11/dbeaver-300x167.png 300w, /wp-content/uploads/2021/11/dbeaver-1024x570.png 1024w, /wp-content/uploads/2021/11/dbeaver-768x428.png 768w, /wp-content/uploads/2021/11/dbeaver-1536x856.png 1536w, /wp-content/uploads/2021/11/dbeaver-750x418.png 750w, /wp-content/uploads/2021/11/dbeaver-1140x635.png 1140w" sizes="(max-width: 1892px) 100vw, 1892px" /></a></p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/dbev.png"><img decoding="async" class="aligncenter size-full wp-image-1375" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/dbev.png" alt="" width="1900" height="904" srcset="/wp-content/uploads/2021/11/dbev.png 1900w, /wp-content/uploads/2021/11/dbev-300x143.png 300w, /wp-content/uploads/2021/11/dbev-1024x487.png 1024w, /wp-content/uploads/2021/11/dbev-768x365.png 768w, /wp-content/uploads/2021/11/dbev-1536x731.png 1536w, /wp-content/uploads/2021/11/dbev-750x357.png 750w, /wp-content/uploads/2021/11/dbev-1140x542.png 1140w" sizes="(max-width: 1900px) 100vw, 1900px" /></a></p>
<h2 data-xid="Download LINQPad">LINQPad</h2>
<p>LINQPad is a software utility targeted at . NET Framework and . NET Core development. It is used to <b>interactively query SQL databases</b> (among other data sources such as OData or WCF Data Services) using LINQ, as well as interactively writing C# code without the need for an IDE.</p>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/linqpad.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1376" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/linqpad.png" alt="" width="834" height="462" srcset="/wp-content/uploads/2021/11/linqpad.png 834w, /wp-content/uploads/2021/11/linqpad-300x166.png 300w, /wp-content/uploads/2021/11/linqpad-768x425.png 768w, /wp-content/uploads/2021/11/linqpad-750x415.png 750w" sizes="(max-width: 834px) 100vw, 834px" /></a> <a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/linqpad2.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1377" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/linqpad2.png" alt="" width="793" height="357" srcset="/wp-content/uploads/2021/11/linqpad2.png 793w, /wp-content/uploads/2021/11/linqpad2-300x135.png 300w, /wp-content/uploads/2021/11/linqpad2-768x346.png 768w, /wp-content/uploads/2021/11/linqpad2-750x338.png 750w" sizes="(max-width: 793px) 100vw, 793px" /></a></p>
<h2>SQL management studio</h2>
<p><a href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/sqlma.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-1378" src="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/wp-content/uploads/2021/11/sqlma.png" alt="" width="1900" height="904" srcset="/wp-content/uploads/2021/11/sqlma.png 1900w, /wp-content/uploads/2021/11/sqlma-300x143.png 300w, /wp-content/uploads/2021/11/sqlma-1024x487.png 1024w, /wp-content/uploads/2021/11/sqlma-768x365.png 768w, /wp-content/uploads/2021/11/sqlma-1536x731.png 1536w, /wp-content/uploads/2021/11/sqlma-750x357.png 750w, /wp-content/uploads/2021/11/sqlma-1140x542.png 1140w" sizes="(max-width: 1900px) 100vw, 1900px" /></a>Well, those were a couple of tools I used and I have been using, and hope this was helpful for you.</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya.com/2021/11/07/tools-i-use-with-database/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1371</post-id>	</item>
		<item>
		<title>Sql tips</title>
		<link>https://achrafbenalaya.com/2020/04/27/sql-tips/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sql-tips</link>
					<comments>https://achrafbenalaya.com/2020/04/27/sql-tips/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Mon, 27 Apr 2020 21:03:19 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[sql]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=477</guid>

					<description><![CDATA[Microsoft SQL Server (and other SQL systems) provide a large amount of data about their servers, users, tables, and stored procedures . During the corona qurantine , I decided to read some books and share with you what I have learned . If part of your daily job is to write sql scripts or manage [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Microsoft SQL Server (and other SQL systems) provide a large amount of data about their servers, users, tables, and stored procedures .</p>
<p>During the corona qurantine , I decided to read some books and share with you what I have learned .</p>
<p>If part of your daily job is to write sql scripts or manage sql server you may want to know more about what’s happening in your envirnment for that , in this blog , I share some of the tips I learned in this book from managing users , memory ,cpu etc…</p>
<p>Link to book : <a href="https://www.syncfusion.com/ebooks/sql-server-metadata-succinctly">https://www.syncfusion.com/ebooks/sql-server-metadata-succinctly</a></p>
<h4 id="memory" class="post-content-header">Memory</h4>
<p>SQL Server is designed to manage memory itself, rather than require administrators to allocate the memory. Basically, SQL will greedily take as much memory as it can get but will release memory to the operating system if the OS is needy (low memory situation). You can use the dm_os_sys_memory view to query the amount of memory on the server.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT [total_physical_memory_kb] / 1024   as  TotalPhysMemoryMB ,   
       [available_physical_memory_kb]/ 1024 as     
       AvailMemoryMB ,[total_page_file_kb]/1024 as 
       PageFileTotalMB ,[available_page_file_kb]/1024 as PageFileAvailMB ,[system_memory_state_desc] FROM [sys].[dm_os_sys_memory]</pre>
<p>The system_memory_state_desc fields indicate whether memory is high (SQL can keep using it) or low (SQL needs to release some to operating system). Ideally, there are not a lot of memory-intensive processes running on the SQL server machine.</p>
<h4>Return hard drive status</h4>
<p>You can use the xp_fixedDrives stored procedure or, starting with SQL 2017, the new Dynamic Management view called dm_os_enumerate_fixed_drives. The stored procedure returns two columns: the drive letter and megabytes free. The new view returns the drive path and drive type (usually fixed or network), and the bytes free.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">if object_id('sys.dm_os_enumerate_fixed_drives') 
   is not null 
   SELECT fixed_drive_path,drive_type_desc, 
   free_space_in_bytes/(1024*1024) as
   MB_Free FROM sys.dm_os_enumerate_fixed_drives 
   else exec xp_fixedDrives</pre>
<h4 id="determine-where-the-various-databases-reside" class="post-content-header">determine where the various databases reside</h4>
<p>I wanted to know where generally does the SQL Server Database reside ?</p>
<p>where can i find log and data files ?</p>
<p>for that this script will Show free space and system and database files.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">IF OBJECT_ID('sys.dm_os_enumerate_fixed_drives') IS NOT NULL
   SELECT
       mf.type_desc,
       mf.name,
       mf.physical_name,
       fd.drive_type_desc,
       fd.free_space_in_bytes / (1024 * 1024) AS MB_Free
   FROM sys.master_files mf
   JOIN sys.dm_os_enumerate_fixed_drives fd
       ON SUBSTRING(mf.physical_name, 1, 3) = fd.fixed_drive_path
   WHERE database_id IN (1, 2, DB_ID())
   ELSE
   BEGIN
   CREATE TABLE #tmpDrives (
       drive char(1),
       free_space_in_bytes bigint
   )
   INSERT INTO #tmpDrives EXEC xp_fixeddrives
   SELECT
       mf.type_desc,
       mf.name,
       mf.physical_name,
       'FIXED' AS
       drive_type_desc,
       ROUND((fd.free_space_in_bytes * 1.0) / 1024, 0) AS MB_Free
   FROM sys.master_files mf
   JOIN #tmpDrives fd
       ON SUBSTRING(mf.physical_name, 1, 1) = fd.drive
   WHERE database_id IN (1, 2, DB_ID())
   DROP TABLE #tmpDrives
   END</pre>
<p>You should expect to see that the log and data files are stored on separate drives, and that the tempdb files (could be multiple files) are on their own drive, as well. While this hard drive configuration could vary, those are the generally recommended guidelines for performance purposes.</p>
<p>SQL Server uses the system registry of the server machine to hold several settings, such as the SQL image, startup parameters, or port. You can use the dm_server_registry view to peek at these registry settings.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT * FROM [sys].[dm_server_registry]</pre>
<h4 id="databases-on-the-server" class="post-content-header">Databases on the server</h4>
<p>A typical SQL server has multiple databases on it, some required by the server and those for your application data. The sys.databases view provides information about all the databases installed on the server.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
   database_id,
   [name],
   create_date,
   CASE compatibility_level
       WHEN 80 THEN 'SQL 2005'
       WHEN 90 THEN 'SQL 2005'
       WHEN 100 THEN 'SQL 2008'
       WHEN 110 THEN 'SQL 2012'
       WHEN 120 THEN 'SQL 2014'
       WHEN 130 THEN 'SQL 2016'
       WHEN 140 THEN 'SQL 2017'
       WHEN 150 THEN 'SQL 2019'
       ELSE 'Unknown version'
   END AS SQL_Level
   FROM sys.databases
   ORDER BY database_id</pre>
<p>The SQL tables are stored in a physical disk file (MDF files), and you can determine the files that are holding the current database tables using the sys.database_files view.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    type_desc,
    name,
    physical_name
    FROM sys.database_files</pre>
<h4 id="settings" class="post-content-header">settings</h4>
<p>You can run queries against the sys.configurations view to get the values of the settings. For example, the following SQL query checks whether CLR (common language runtime assemblies) are allowed on this server.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT * FROM sys.configurations WHERE [name]='clr enabled'

EXEC sp_configure 'clr enabled'

EXEC sp_configure 'clr enabled',1</pre>
<p>SQL administrators will generally use scripts of sp_configure commands to configure the server.</p>
<p>With the CLR hosted in Microsoft SQL Server (called CLR integration), you can author stored procedures, triggers, user-defined functions, user-defined types, and user-defined aggregates in managed code. Because managed code compiles to native code prior to execution, you can achieve significant performance increases in some scenarios.</p>
<p>more : <a href="https://docs.microsoft.com/en-us/sql/relational-databases/clr-integration/common-language-runtime-integration-overview?view=sql-server-ver15">https://docs.microsoft.com/en-us/sql/relational-databases/clr-integration/common-language-runtime-integration-overview?view=sql-server-ver15</a></p>
<h4 id="serverproperty" class="post-content-header">SERVERPROPERTY</h4>
<p>The SERVERPROPERTY function also provides a good deal of information about the server. It takes a single parameter, the property name, and returns the current property value. For example, the following code snippet shows the edition of SQL Server being run.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">select SERVERPROPERTY(‘edition’) as ServerEdition


</pre>
<h5>ServerProperties :</h5>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
'SQL Server: ' AS Label,
SERVERPROPERTY('ProductVersion') AS Version,
SERVERPROPERTY('edition') AS ServerEdition,
SERVERPROPERTY('productLevel') AS ServerEdition,
SERVERPROPERTY('MachineName') AS Machine,
CASE SERVERPROPERTY('IsIntegratedSecurityOnly')
    WHEN 0 THEN 'SQL and Windows logins'
    ELSE 'Windows Authentication'
END AS AuthMode</pre>
<h4 id="sysdatabases" class="post-content-header">Sys.databases</h4>
<p>The primary view for database information is the sys.databases view. This view holds a row of information for each database in the server.</p>
<p>SELECT * from sys.databases WHERE database_id=db_id()</p>
<p>The function db_id() returns the numeric ID of the current database</p>
<p>The General tab of the Properties page provides some simple status information, such as database size and date of the last backup. This information can be assembled using the sys.databases view and the DATABASEPROPERTYEX() function. the sys.databases view and DATABASEPROPERTYEX() function to duplicate much of the information from the General tab</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    db.name AS databaseName,
    DATABASEPROPERTYEX(db.name, 'Status')
    AS 'Status',
    su.Name AS 'Owner',
    db.create_date AS 'Date Created',
    CONVERT(varchar, mf.size * 8 / 1024) + ' MB'
    AS [Total disk space]
    FROM sys.databases db
    JOIN (SELECT
    database_id,
    SUM(size) AS Size
    FROM sys.master_files
    GROUP BY database_id) mf
    ON db.database_id = mf.database_id
    LEFT JOIN sys.sql_logins su
    ON su.sid = db.owner_sid

    WHERE db.database_Id=db_Id()</pre>
<p><img loading="lazy" decoding="async" class="aligncenter size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/sqlmars/sql4.png" width="849" height="579" /></p>
<h4 id="backup-information" class="post-content-header">Backup information</h4>
<p>The backup information is retrieved from the backupset table in the MSDB (Microsoft Database) database. We can retrieve the backup information for both the data and the logs</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    CASE type
        WHEN 'D' THEN 'Database'
        WHEN 'L' THEN 'Logs'
    END AS BackupType,
    MAX(backup_finish_date) AS LastBackup
    FROM msdb.dbo.backupset
    WHERE database_name = DB_NAME()
    GROUP BY database_name,
            type</pre>
<p>There is other information available in the backupset table, such as the backup size, whether it is encrypted or not, recovery model, compressed size, etc. Although we are only interested in the backup dates, you might find occasional need to access the other fields.</p>
<h4 id="size-information" class="post-content-header">Size information</h4>
<p>The size of any database can be retrieved easily from the sys.master_files view, but the actual use (needed to compute space available) requires a bit more effort. Code Listing 20 provides this information.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    DB_NAME() AS database_name,
    LTRIM(STR((CASE
        WHEN sf.dbsize &gt;= pt.reservedpages THEN (CONVERT(decimal(15, 2), sf.dbsize) - CONVERT(decimal(15, 2), pt.reservedpages)) * 8192 / 1048576
        ELSE 0
    END), 15, 2) + ' MB') AS 'Space Available'
    FROM (SELECT
        SUM(CONVERT(bigint, CASE
            WHEN sf.STATUS &amp; 64 = 0 THEN size
            ELSE 0
        END)) AS dbSize
        FROM dbo.sysfiles sf) AS sf,
        (SELECT
        reservedpages = SUM(a.total_pages)
        FROM sys.partitions p
        INNER JOIN sys.allocation_units a
        ON p.partition_id = a.container_id) AS pt</pre>
<p>Also , you can check the information about the database files and growth is available from the sysFiles view</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    sf.[name] AS Logical_Name,
    CASE
        WHEN Status = 2 THEN 'ROWS Data'
        WHEN Status = 66 THEN 'LOG'
    END AS FileType,
    ISNULL(fg.type_desc, 'Not Applicable') AS FileGroup,
    size * 8.0 / 1024 AS 'Current Size (MB)',
    growth * 8.0 / 1024 AS 'Autogrowth (MB)',
    CASE
        WHEN maxsize = 0 THEN 'No growth'
        WHEN maxsize &lt; 0 THEN 'Unlimited'
        WHEN maxsize * 8.0 / 1024 &gt;= CAST(268435456 / 8 AS bigint) THEN '2 TerraBytes'
        ELSE CAST(ROUND(maxsize * 8.0 / 1024, 0) AS varchar(20)) + 'MB'
    END AS MaxSize,
    FileName AS 'Path'
    FROM sys.sysfiles sf
    LEFT JOIN sys.filegroups fg
    ON fg.data_space_id = sf.fileid</pre>
<p><img loading="lazy" decoding="async" class="alignnone size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/sqlmars/sql5.png" width="945" height="450" /></p>
<h3 id="section-who" class="post-content-header">Section who</h3>
<h4 id="who-can-edit" class="post-content-header">Who can edit?</h4>
<p>This script give you information list of all users, roles, groups, etc., that can manipulate data with your database</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
   pr.name,
   pr.type,
   p.permission_name
   FROM sys.database_permissions p
   JOIN sys.database_principals pr
   ON pr.principal_id = p.grantee_principal_id
   WHERE permission_name IN ('DELETE', 'UPDATE', 'INSERT')
   AND state = 'G'</pre>
<h4 id="who-can-select-database-objects" class="post-content-header">Who can select database objects ?</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    pr.name,
    pr.type,
    p.permission_name,
    OBJECT_NAME(major_id) AS AllowedView
    FROM sys.database_permissions p
    JOIN sys.database_principals pr
    ON pr.principal_id = p.grantee_principal_id
    WHERE permission_name IN ('SELECT')
    AND p.state = 'G'
    ORDER BY AllowedView</pre>
<h4 id="what-can-the-public-role-do" class="post-content-header">What can the public role do ?</h4>
<p>You might also want to see what rights the public role has, since all users inherit these rights</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    p.permission_name,
    OBJECT_NAME(major_id)
    AS AllowedView
    FROM sys.database_permissions p
    JOIN sys.database_principals pr
    ON pr.principal_id = p.grantee_principal_id

    WHERE pr.name = 'Public'
    AND state = 'G'
    AND class &lt;&gt; 0
    ORDER BY AllowedView</pre>
<h4 id="list-all-identity-columns" class="post-content-header">List all identity columns</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    OBJECT_SCHEMA_NAME(st.object_id) + '.' + st.name AS [TableName],
    ic.name AS KeyName,
    t.name AS dataType,
    ic.seed_value,
    ic.increment_value,
    ISNULL(ic.last_value, 0) AS Last_Value
    FROM sys.tables st
    JOIN sys.identity_columns ic
    ON ic.object_id = st.object_id
    JOIN sys.types t
    ON t.system_type_id = ic.system_type_id
    ORDER BY [TableName]</pre>
<p>This listing shows tables that have an Identity column, along with the seed value and increment for the column. If the table has rows, the Last_value column will report the last seed number.</p>
<h4 id="default-constraints" class="post-content-header">default constraints</h4>
<p>A database table may have a default value to provide during an INSERT when the corresponding field is NULL. The following script lists all the default constraints and the table and columns they are found in.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    OBJECT_SCHEMA_NAME(dc.parent_object_id) + '.' + OBJECT_NAME(dc.parent_object_id) AS TableName,
    c.name AS ColumnName,
    dc.definition
    FROM sys.default_constraints AS dc
    INNER JOIN sys.columns AS c
    ON dc.parent_object_id = c.object_id
    AND dc.parent_column_id = c.column_id
    ORDER BY tableName, columnName</pre>
<h4 id="sysindex" class="post-content-header">sys.index</h4>
<p>This script will identify all the columns that are used as indexes in the various tables. This can be a handy way to determine whether a new search you want to add is already indexed in the table</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
   st.name AS TableName,
   i.name AS IndexName,
   COL_NAME(ic.object_id, ic.column_id) AS ColumnName
   FROM sys.indexes AS i
   INNER JOIN sys.index_columns AS ic
   ON i.object_id = ic.object_id
   AND i.index_id = ic.index_id
   JOIN sys.tables st
   ON st.object_id = ic.object_id
   ORDER BY [TableName], ic.index_column_id, ColumnName</pre>
<h4 id="syscheck_constraints" class="post-content-header">sys.check_constraints</h4>
<p>A check constraint is a SQL expression that is applied to a column to validate the type of data allowed in that column. For example, you might use the following LIKE expression to ensure a zip code field only contains five digits. zip LIKE ‘[0-9][0-9][0-9][0-9][0-9]&#8217;. List all check constraints</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    OBJECT_SCHEMA_NAME(dc.parent_object_id) + '.' + OBJECT_NAME(dc.parent_object_id) AS TableName,
    c.name AS ColumnName,
    dc.definition
    FROM sys.check_constraints AS dc
    INNER JOIN sys.columns AS c
    ON dc.parent_object_id = c.object_id
    AND dc.parent_column_id = c.column_id
    ORDER BY tableName, columnName</pre>
<h4 id="report" class="post-content-header">Report</h4>
<p>to produce a report of tables and columns in your system, along with column information.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    OBJECT_SCHEMA_NAME(tb.object_id) + '.' + OBJECT_NAME(tb.object_id) AS TableName,
    c.name AS ColumnName,
    ISNULL(pk.PK, '') AS IsKey,
    ISNULL(ic.IdentityColumn, '') AS Identity_Column,
    ISNULL(cc.CheckConstraint, '') AS Check_Constraint,
    ISNULL(dc.DefaultConstraint, '') AS Default_Constraint
    FROM sys.tables AS tb
    JOIN sys.columns AS c
    ON c.object_id = tb.object_id
    LEFT JOIN (SELECT
    ic.object_id,
    ic.index_column_id,
    'PRIMARY' AS PK
    FROM sys.tables tb
    JOIN sys.key_constraints kc
    ON kc.parent_object_id = tb.object_id
    JOIN sys.index_columns ic
    ON ic.object_id = kc.parent_object_id
    AND kc.unique_index_id = ic.index_id
    WHERE tb.type = 'U'
    AND kc.type = 'PK') pk
    ON pk.object_id = tb.object_id
    AND pk.index_column_id = c.column_id
    LEFT JOIN (SELECT
    ic.object_id,
    ic.name,
    ic.name + ' identity(' +
    CAST(ic.seed_value AS varchar(10)) + ',' + CAST(ic.increment_value AS varchar(10)) + ') ' AS IdentityColumn
    FROM sys.tables st
    JOIN sys.identity_columns ic
    ON ic.object_id = st.object_id) ic
    ON tb.object_id = ic.object_id
    AND c.name = ic.name
    LEFT JOIN (SELECT
    dc.parent_object_id,
    dc.parent_column_id,
    dc.definition AS CheckConstraint
    FROM sys.check_constraints AS dc
    INNER JOIN sys.columns AS c
    ON dc.parent_object_id = c.object_id
    AND dc.parent_column_id = c.column_id) cc
    ON cc.parent_object_id = tb.object_id
    AND cc.parent_column_id = c.column_id
    LEFT JOIN (SELECT
    dc.parent_object_id,
    dc.parent_column_id,
    dc.definition AS DefaultConstraint
    FROM sys.default_constraints AS dc
    INNER JOIN sys.columns AS c
    ON dc.parent_object_id = c.object_id
    AND dc.parent_column_id = c.column_id) dc
    ON dc.parent_object_id = tb.object_id
    AND dc.parent_column_id = c.column_id
    ORDER BY tableName, column_id</pre>
<h4 id="searching-for-deprecated-columns" class="post-content-header">Searching for deprecated columns</h4>
<p>In early versions of SQL, there were text and image columns called text, nText, and image. These columns (while still supported) were deprecated in SQL Server 2005. The following script allows you to search for deprecated column types and indicates the appropriate replacement column type.</p>
<p>List all columns with deprecated types :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    t.name,
    c.name AS ColName,
    'Deprecated: ' + CASE
        WHEN tp.name = 'text' THEN 'Replace  with varchar(max)'
        WHEN tp.name = 'ntext' THEN 'Replace [ntext] with nvarchar(max)'
        WHEN tp.name = 'image' THEN 'Replace [image] with varbinary(max)'
        ELSE 'Table contains Text,nText, or Image fields'
    END AS Msg
    FROM sys.columns c
    JOIN sys.tables t
    ON c.object_id = t.object_id
    JOIN sys.types tp
    ON tp.user_type_id = c.user_type_id
    WHERE t.is_ms_shipped = 0
    AND tp.name IN ('text', 'ntext', 'image')</pre>
<p>If you are using any of these column data types, you should plan on changing the data type to keep current with SQL Server.</p>
<h4 id="perfermance" class="post-content-header">Perfermance</h4>
<p>The view sys.sysprocesses provides a list of all connections currently open on the server. the below Table lists some of the columns you can use to query this view.</p>
<table style="height: 804px;" width="673">
<thead>
<tr>
<th><strong>Column name</strong></th>
<th><strong>Description</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<h5>spid</h5>
</td>
<td>
<h5>SQL Server session ID</h5>
</td>
</tr>
<tr>
<td>
<h5>kpid</h5>
</td>
<td>
<h5>Windows thread ID.</h5>
</td>
</tr>
<tr>
<td>
<h5>blocked</h5>
</td>
<td>
<h5>spid of session blocking this process</h5>
</td>
</tr>
<tr>
<td>
<h5>waittime</h5>
</td>
<td>
<h5>How long process has been waiting (milliseconds) or 0.</h5>
</td>
</tr>
<tr>
<td>
<h5>lastwaittype</h5>
</td>
<td>
<h5>String description of last wait encountered.</h5>
</td>
</tr>
<tr>
<td>
<h5>dbid</h5>
</td>
<td>
<h5>Database ID (use db_name() to see name) of database.</h5>
</td>
</tr>
<tr>
<td>
<h5>cpu</h5>
</td>
<td>
<h5>Cumulative CPU usage time for this process.</h5>
</td>
</tr>
<tr>
<td>
<h5>physical_io</h5>
</td>
<td>
<h5>Cumulative disk reads/writes.</h5>
</td>
</tr>
<tr>
<td>
<h5>memusage</h5>
</td>
<td>
<h5>Current number of memory pages allocated to process.</h5>
</td>
</tr>
<tr>
<td>
<h5>login_time</h5>
</td>
<td>
<h5>When this process was logged in.</h5>
</td>
</tr>
<tr>
<td>
<h5>last_batch</h5>
</td>
<td>
<h5>Last time a statement was run by process.</h5>
</td>
</tr>
<tr>
<td>
<h5>open_tran</h5>
</td>
<td>
<h5>Current number of open transactions used by this process.</h5>
</td>
</tr>
<tr>
<td>
<h5>open_tran</h5>
</td>
<td>
<h5>Current number of open transactions used by this process.</h5>
</td>
</tr>
<tr>
<td>
<h5>status</h5>
</td>
<td>
<h5>String description of current status Running Background Runnable Sleeping</h5>
</td>
</tr>
<tr>
<td>
<h5>hostname</h5>
</td>
<td>
<h5>Name of the workstation.</h5>
</td>
</tr>
<tr>
<td>
<h5>program_name</h5>
</td>
<td>
<h5>Name of the application.</h5>
</td>
</tr>
<tr>
<td>
<h5>cmd</h5>
</td>
<td>
<h5>Type of command being executed (SELECT, DELETE, etc.).</h5>
</td>
</tr>
<tr>
<td>
<h5>nt_domain</h5>
</td>
<td>
<h5>Windows domain, if using Windows authentication.</h5>
</td>
</tr>
<tr>
<td>
<h5>nt_username</h5>
</td>
<td>
<h5>Username, if Windows authentication or trusted connection.</h5>
</td>
</tr>
<tr>
<td>
<h5>loginname</h5>
</td>
<td>
<h5>User’s login name.</h5>
</td>
</tr>
<tr>
<td>
<h5>sql_handle</h5>
</td>
<td>
<h5>Memory pointer to the currently executing command.</h5>
</td>
</tr>
<tr>
<td>
<h5>stmt_end</h5>
</td>
<td>
<h5>Ending offset for current statement.</h5>
</td>
</tr>
<tr>
<td>
<h5>stmt_start</h5>
</td>
<td>
<h5>Offset into handle of current statement.</h5>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>The information in this table provides the ability to determine what exactly the server is doing, and who is doing it. Some example usages appear in the next few queries. Note that dbid of 1 through 4 are system databases, so activity in those databases is typically done by SQL Services. Database ID number 2 is tempdb, which might be worth checking out if you hit performance issues.</p>
<h4 id="who-is-running-sql-management-studio" class="post-content-header">Who is running SQL Management Studio?</h4>
<p>SQL Management Studio allows users to run queries, updates, etc., in a database. Typically, developers and database administrators will be using this tool. Any other users might be worth reviewing.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    loginame,
    login_time,
    cmd
    FROM sys.sysprocesses
    WHERE dbid &gt; 4
    AND program_name LIKE '%SQL Server Man%'
    ORDER BY loginame</pre>
<h4 id="who-is-blocking-others" class="post-content-header">Who is blocking others?</h4>
<p>You can see who might be blocking other processes</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    'Process ' + STR(sp.spid) + ', user ' + sp.loginame + ' is being blocked by ' + STR(bl.spid) + ' user ' + bl.loginame AS BlockedMsg
    FROM sys.sysprocesses sp
    JOIN sys.sysprocesses bl
    ON sp.blocked = bl.spid
    WHERE sp.dbid &gt; 4
    AND sp.blocked &lt;&gt; 0</pre>
<h4 id="who-has-open-transactions" class="post-content-header">Who has open transactions ?</h4>
<p>If a user has a transaction open, the tables impacted within that transaction will block other update operations (and possibly select statements, depending on isolation level).</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
    'Process ' + LTRIM(STR(sp.spid)) + ', user ' + sp.loginame + ' has ' + STR(sp.open_tran) + ' open transactions'
    FROM sys.sysprocesses sp
    WHERE sp.dbid &gt; 4
    AND sp.open_tran &lt;&gt; 0</pre>
<h4 id="what-are-they-doing" class="post-content-header">What are they doing ?</h4>
<p>The sql_handle column in the view provides the ability to see what is being done by the session. You can use the sys.dm_exec_sql_text table-valued function to look at the actual work being done.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
   sp.spid,
   sp.loginame,
   st.text
   FROM sys.sysprocesses sp
   CROSS APPLY sys.dm_exec_sql_text(sp.sql_handle) st
   WHERE sp.dbid &gt; 4
   AND sql_handle &lt;&gt; 0</pre>
<h4 id="worst-cpu-usage" class="post-content-header">Worst CPU usage</h4>
<p>CPU time is measured by the worker_time value, so we can order by total worker time to identify those plans using a lot of CPU time.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT TOP 5
    st.text AS SrcCode,
    qp.query_plan,
    qs.execution_count,
    qs.last_execution_time
    FROM sys.dm_exec_query_stats qs
    CROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) st
    CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp

    ORDER BY total_worker_time DESC</pre>
<p>&nbsp;</p>
<h4 id="worst-io" class="post-content-header">Worst I/O</h4>
<p>The input/output (I/O) totals indicate how often a query needs to read something from the disk. Ideally, in a query, you should read the minimum amount of data needed. When a query uses SELECT * or a lot of table scans, SQL is bringing back more data than is needed. For example, imagine a personnel table that includes a binary image of the person. If your code does a SELECT * from this table, but only displays the name and phone number, you’ve had SQL bring back extra data (the binary image, among other fields), when all it needed was two fields.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT TOP 5
   st.text AS SrcCode,
   qp.query_plan,
   qs.execution_count,
   qs.last_execution_time
   FROM sys.dm_exec_query_stats qs
   CROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) st
   CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
   ORDER BY total_logical_reads DESC</pre>
<h4 id="is-another-processing-blocking-your-query" class="post-content-header">Is another processing blocking your query?</h4>
<p>You can investigate the sys.dm_os_waiting_tasks view for the blocked column of your target spid. If some other process is blocking your query, focus on the blocker first. Similarly, if another query has open transactions, that might be the culprit slowing your query down.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT
   wait_type,
   blocking_session_id,
   p.program_name,
   p.loginame
   FROM sys.dm_os_waiting_tasks wt
   JOIN sys.sysprocesses p
   ON p.sid = wt.blocking_session_id
   WHERE session_id = @@spid</pre>
<h4 id="finally-the---like-clause" class="post-content-header">finally the : LIKE clause</h4>
<p>The LIKE clause is a powerful SQL feature, allowing a person to find “matches” in a table, rather than exact values. However, it is possible to create a condition where SQL must use a table scan (slower) rather than any indexes to resolve the like expression. This can impact performance when applying the like clause to large tables.</p>
<p>If you were creating a system to allow people to search by last name, you might want to use LIKE as shown in the following.</p>
<blockquote><p><code>Beginning with =&gt; LIKE ‘Mc%’<br />
</code></p>
<p><code>    Ending with =&gt; LIKE ‘%son’</code></p></blockquote>
<p>The first LIKE clause will use an index (assuming one exists on the last name column). However, the second clause will require a table scan, which can slow performance by quite a bit. To the user of the system, though, the difference might not be understandable as to why one search is quick and the other quite slow.</p>
<p>Hope you enjoyed learning those tips .</p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya.com/2020/04/27/sql-tips/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">477</post-id>	</item>
		<item>
		<title>Sql tips and tricks</title>
		<link>https://achrafbenalaya.com/2020/04/26/sql-tips-and-tricks/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sql-tips-and-tricks</link>
					<comments>https://achrafbenalaya.com/2020/04/26/sql-tips-and-tricks/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Sun, 26 Apr 2020 20:40:47 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[sql]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=463</guid>

					<description><![CDATA[I’m super excited to write my first article in tips and tricks section about sql . if you’re pursuing a job as a back-end developer or if you simply work with data (data scientist, data engineer.., whatever you want to call it) it means you will work with sql , tables , procedure,views etc… In [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I’m super excited to write my first article in tips and tricks section about sql . if you’re pursuing a job as a back-end developer or if you simply work with data (data scientist, data engineer.., whatever you want to call it) it means you will work with sql , tables , procedure,views etc…</p>
<p>In this short article I’m going to share with you few tips I learned past days.</p>
<p>Last week , and after I have updated an old version of source code and procedures at work , I thought i finished my work , but nah I didn’t .</p>
<p>Of course there is no problems In code (hopefully , cause test team is gonna start testing the code next week <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f91e.png" alt="🤞" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ) when we push the source code , it will be the same for all the clients , but , I only have updated the procedure in one database for one client , and there is like 15 to 20 client ! I forget about that !</p>
<p>&nbsp;</p>
<p>So , what should I do here , should I go to each database, look for the procedures inside the stored procedures folder and do ALTER PROCEDURE ?</p>
<p>That’s just waste of time and thank to one of my college at work , I learned how to do that In a better way .</p>
<p>for that I’m gonna show you how to create a table , insert data , create procedure , look for that procedure and update it in easy way .</p>
<p>so let’s get started .</p>
<h4 id="create-table" class="post-content-header">Create Table</h4>
<p>Here we are going to create a Table called person and we are going to fill it with random data :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">CREATE TABLE person 
  ( 
     firstname   VARCHAR(50), 
     lastname    VARCHAR(50), 
     gender      VARCHAR(50), 
     phonenumber VARCHAR(50), 
     city        VARCHAR(50), 
     urd         DATETIME DEFAULT (Getdate()) 
  )</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">INSERT INTO person 
            (firstname, 
             lastname, 
             gender, 
             phonenumber, 
             city) 
VALUES     (‘heero’, 
            ‘yuy’, 
            ‘male’, 
            ‘888888’, 
            ‘london’) 

INSERT INTO person 
            (firstname, 
             lastname, 
             gender, 
             phonenumber, 
             city) 
VALUES     (‘relena’, 
            ‘darlian’, 
            ‘female’, 
            ‘888888’, 
            ‘london’) 

INSERT INTO person 
            (firstname, 
             lastname, 
             gender, 
             phonenumber, 
             city) 
VALUES     (‘messi’, 
            ‘lionel ‘, 
            ‘male’, 
            ‘888888’, 
            ‘rosario’) 

INSERT INTO person 
            (firstname, 
             lastname, 
             gender, 
             phonenumber, 
             city) 
VALUES     (‘cristiano’, 
            ‘ronaldo’, 
            ‘male’, 
            ‘888888’, 
            ’ funchal’)</pre>
<p>Now after populating the data if we see what’s inside our Table by using :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">select * from Person
</pre>
<p>we will find that our table now contain this data :</p>
<p><img loading="lazy" decoding="async" class="alignnone size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/post2/image1.png" width="592" height="162" /></p>
<p>now let’s say we want to get all the persons where city = London , it’s easy to write</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT * FROM person WHERE city = ‘London’</pre>
<p>but as a backend developer you know that you are going to create a Stored Procedure or you are going to use Entity Framework .</p>
<h4 id="stored-procedure" class="post-content-header">Stored Procedure</h4>
<p>To write a simple stored procedure that will return the persons where city is London we have to write this simple procedure :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">CREATE PROCEDURE Selectallcustomers @city NVARCHAR(30) 
AS 
    SELECT * 
    FROM   person 
    WHERE  city = @city</pre>
<p>To test this procedure all you have to do is to run it using EXEC , how is that ? it’s simple !</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">EXEC SelectAllCustomers ‘London’
</pre>
<p>Excec will execute the procedure SelectAllCustomers using the parameter ‘London’ which is the</p>
<p>city we are looking for , and as result we will get :</p>
<p><img loading="lazy" decoding="async" class="alignnone size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/post2/image2.png" width="519" height="85" /></p>
<p>Easy ? right !!</p>
<p>Now , let’s say that this procedure exist in 20 database ,like for 20 client, the project manager now ask you to changed that procedure cause they need not only persons where city equals London but also the gender of those person is Male .</p>
<p>Now your not gonna start looking for that procedure manually in each database cause you are going to loose a lot of time in something that will only take few minutes (I used to loose all that time , don’t be shy , we’re all still learning )</p>
<p>Now first step is to create or update that procedure as we are asked for :</p>
<p>The old procedure is :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">
CREATE PROCEDURE Selectallcustomers @city NVARCHAR(30) 
AS 
    SELECT * 
    FROM   person 
    WHERE  city = @city</pre>
<p>now Let’s change it and we add that the Gender is Male :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">CREATE PROCEDURE Selectallcustomers @city NVARCHAR(30) 
AS 
select * FROM person WHERE city = @city AND gender =’male’</pre>
<p>now if you try to execute this procedure again you will get an error like this :</p>
<p><img loading="lazy" decoding="async" class="alignnone size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/post2/image3.png" width="654" height="60" /></p>
<p>That mean that the procedure does exist in the database and you can not insert that procedure with the same name , now don’t think we are going to rename that database , and like that we will have a ton of unused procedures in our database .</p>
<p>to update this procedure , we need to drop it first than replace it with the new one .</p>
<p>First , let’s check with a simple command if the procedure exist in our database .</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N’[SelectAllCustomers]') 
AND type in (N’P’, N’PC’,‘FN’,‘TF’)) 
SELECT ‘found’ AS search_result ELSE SELECT ‘not found’ AS search_result;</pre>
<p>Now ,what will this code do is , to look inside the sys.objects and see if the object or the procedure SelectAllCustomers exist , if exist it will return found , else it will return as search result not found . We can make the result of this as we want it , for example we can return 1 if exist and 0 if not , but it is nicer to get a clean result that another person can understand , cause other may not understand 0 and 1 and their meaning .</p>
<p><img loading="lazy" decoding="async" class="alignnone size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/post2/image4.png" width="147" height="76" /></p>
<p>Now , after checking that the procedure exist , let’s update it :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N’[SelectAllCustomers]')
 AND type in (N’P’, N’PC’,‘FN’,‘TF’)) 
DROP PROCEDURE SelectAllCustomers 
GO
 CREATE PROCEDURE SelectAllCustomers @city nvarchar(30) AS SELECT * FROM person WHERE city = @city and gender ='Male’</pre>
<p>Now , don’t get overwhelmed , I will explain it all .</p>
<p>The first line will check if the procedure SelectAllCustomers is a stored procedure (P) or a assembly stored procedure (PC).. that exist in the db . If that procedure exist the command DROP PROCEDURE will delete that procedure and after it , we will create a new one .</p>
<p>Easy ? right !</p>
<h4 id="more-tricks-" class="post-content-header">More tricks !</h4>
<p>If you want to see if a table exist in the database you can execute this block and don’t forget to change the name of the table with yours</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">IF EXISTS( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ‘Person’ )
 SELECT ‘found’ AS search_result ELSE SELECT ‘not found’ AS search_result;</pre>
<p>If you want to get all the columns of a table you can execute this block :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ‘Person’</pre>
<p><img loading="lazy" decoding="async" class="alignnone size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/post2/image5.png" width="209" height="182" /></p>
<p>If you are looking if there is a table ‘person’ witha column name like ‘Gender’ you can type :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">IF EXISTS( SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ‘Person’ and COLUMN_NAME='gender’) 
SELECT ‘found’ AS search_result ELSE SELECT ‘not found’ AS search_result</pre>
<p>Now that was the first post , more are coming next weeks .</p>
<p>Happy SQL day =)</p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya.com/2020/04/26/sql-tips-and-tricks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">463</post-id>	</item>
		<item>
		<title>How To Send Mail Using SQL Server</title>
		<link>https://achrafbenalaya.com/2020/04/20/how-to-send-mail-using-sql-server/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-send-mail-using-sql-server</link>
					<comments>https://achrafbenalaya.com/2020/04/20/how-to-send-mail-using-sql-server/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Mon, 20 Apr 2020 23:19:27 +0000</pubDate>
				<category><![CDATA[sql]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=401</guid>

					<description><![CDATA[HI sql developers , Few days ago , when I was working on my new blog , I was thinking about a way to receive and email when a new row is inserted into a specific table in sql server, I was looking for a cheap way to do that , not only because I [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>HI sql developers ,</p>
<p>Few days ago , when I was working on my new blog , I was</p>
<p>thinking about a way to receive and email when a new row is inserted into a specific table in sql server, I was looking for a cheap way to do that , not only because I don’t have money , but also in my country there is no online payment system or cards to use SMTP service providers like SendGrid.</p>
<p>So when I was looking arround , I found out that I can send emails , using Sql Server ! really ? is this even possible ?</p>
<p>And everytime I got questions like that , I usually give it a try , because if you never try , you will never know “‘just don’t try walking in the dark when you move to a new house , believe me you will regret it “’ .</p>
<p>So to make this work , and for this article , we will explain how to configure sql-server to send email , and actually send one .</p>
<p>Ps : all the steps we are going to use are going to be using sql scripts (you can run those scripts even if you have no experience using sql scripts )</p>
<p>First we need to Create a Database Mail profile</p>
<p><strong>profile</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = ‘Notifications’,
@description = ‘Profile used for sending outgoing notifications using Gmail.’ ;
GO</pre>
<p>Next we need to Grant access to the profile to the DBMailUsers role</p>
<p><strong>access</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = ‘Notifications’,
@principal_name = ‘public’,
@is_default = 1 ; GO</pre>
<p>After that we need to Create a Database Mail account</p>
<p><strong>account</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">EXECUTE msdb.dbo.sysmail_add_account_sp
@account_name = ‘Gmail’,
@description = ‘Mail account for sending outgoing notifications.',
@email_address = ‘email@gmail.com’,
@display_name = ‘Automated Mailer’,
@mailserver_name = ‘smtp.gmail.com’, @port = 465, @enable_ssl = 1, @username = ‘Use a valid e-mail address’, @password = ‘email_password ;
GO</pre>
<p>Final step is to Add the account to the profile</p>
<p><strong>profile</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = ‘Notifications’,
@account_name = ‘Gmail’,
@sequence_number =1 ;
GO</pre>
<p>Now we can try sending an email</p>
<p><strong>send_dbmail</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'email@gmail.com',
    @recipients = 'recipientsemail@gmail.com',
   @body = 'The database mail configuration was completed successfully.',
     @subject = 'Automated Success Message';
   GO</pre>
<p>&nbsp;</p>
<p>To see all the configurations that you have on your sql server you can use :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">SELECT *FROM msdb.dbo.sysmail_account
SELECT *FROM msdb.dbo.sysmail_configuration
SELECT *FROM msdb.dbo.sysmail_principalprofile
SELECT *FROM msdb.dbo.sysmail_profile
SELECT *FROM msdb.dbo.sysmail_profileaccount
SELECT *FROM msdb.dbo.sysmail_profileaccount</pre>
<p><img loading="lazy" decoding="async" class="aligncenter size-medium" src="https://achrafbenalaya.github.io/Achrafbenalayablog/img/post14/proofmail1.png" width="1128" height="157" /></p>
<p>&nbsp;</p>
<p>In the next article we will see how to trigger this ,when a new row is inserted , an email will be sent .</p>
<p>You can read more about sp_send_dbmail from Microsoft official <a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql?view=sql-server-ver15">documentation </a></p>
<div class="post-content">
<p>Happy SQL day =)</p>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya.com/2020/04/20/how-to-send-mail-using-sql-server/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">401</post-id>	</item>
	</channel>
</rss>
