<?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 tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/sql-tips/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Thu, 16 Feb 2023 07:10:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>sql tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Reduce Connection Pools Hitting Multiple Databases</title>
		<link>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/</link>
					<comments>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 16 Feb 2023 07:09:12 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[database issue]]></category>
		<category><![CDATA[fix connection pool issue]]></category>
		<category><![CDATA[sql database]]></category>
		<category><![CDATA[sql database hang]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql tips]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3434</guid>

					<description><![CDATA[Microsoft’s connection pooling built in to the .Net Framework greatly improves performance by allowing hundreds of database calls to share the same pool of connections used to connect to the database. The .Net Framework creates a new pool of connections for each unique connection string. This works fantastic when your web application connects to a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Microsoft’s connection pooling built in to the .Net Framework greatly improves performance by allowing hundreds of database calls to share the same pool of connections used to connect to the database. The .Net Framework creates a new pool of connections for each unique connection string. This works fantastic when your web application connects to a single database and all your connections use the same connection string. It even works well if you have two or three different connection strings, but for each unique connection string value, the .Net Framework creates a new connection pool. If your web site has dozens of different databases to connect to, you may find your application creates dozens of connection pools which begins to consume a lot of resources on both the web server and SQL Server.</p>



<p>There is a fairly easy way to eliminate this problem, and that is to use the ChangeDatabase method on the Connection object.</p>



<p>Our web application was connecting to one of fifty different databases that all reside on the same instance of SQL Server. Each of our clients has their own database. But our application was creating fifty different connection pools. We were able to have all the clients share a single pool of connections by first connecting to a neutral database, then redirecting the connection to the desired database.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.asphostportal.com" target="_blank" rel="noreferrer noopener"><img fetchpriority="high" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure></div>


<p>We created a new database on the server, called Central, then we had all the connections to the database first connect to Central as the Initial Catalog. The next step was to call ChangeDatabase to switch to the desired database. This technique did not create a new connection to SQL Server and did not create a new connection pool on the .Net client. Microsoft documentation mentions this technique here: <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases" target="_blank" rel="noreferrer noopener">https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases</a> , but their example code does not show the ChangeDatabase method, which is more efficient than their example.</p>



<p>In a nutshell, you can do this:</p>



<pre class="wp-block-code"><code>connection.Open();
connection.ChangeDatabase(“Client1”);</code></pre>



<p>I created a simple Windows Form App to test the idea.  The test app runs a query to return the name of the current database it is in.  Also, on the SQL Server I run a query to see all the connections that exist.  Doing this I was able to prove that using ChangeDatabase did not create a new connection to SQL Server and my .Net SQL Connection Object was pointing at the correct desired database.  Sample code, query, and output is below:</p>



<p>Sample C# .Net Forms App:</p>



<pre class="wp-block-code"><code>using System;
using System.Data.SqlClient;
using System.Windows.Forms;
 
namespace SQLConnectionTest
{
    public partial class Form1 : Form
    {
        //https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling#pool-fragmentation-due-to-many-databases
        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=model;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=msdb;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            { 
                connection.Open();
                connection.ChangeDatabase("TempDb");
                RunSQL(connection, "select DB_NAME()");
            }
 
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                RunSQL(connection, "select DB_NAME()");
            }
            using (SqlConnection connection = new SqlConnection(@"Server=.\;Database=master;Trusted_Connection = yes"))
            {
                connection.Open();
                connection.ChangeDatabase("TempDb");
                RunSQL(connection, "select DB_NAME()");
                connection.ChangeDatabase("model");
                RunSQL(connection, "select DB_NAME()");
            }
        }
 
        public static void RunSQL(SqlConnection connection, string queryString)
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            try
            {
                SqlDataReader reader = command.ExecuteReader(); 
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("\t{0}", reader[0]);
                    }
                    reader.Close();
                }
            }
            catch (Exception ex){Console.WriteLine(ex.Message);}
        }
        public Form1()
        {
            InitializeComponent();
        }
 
 
    }
}</code></pre>



<p>Output from Running the App written to console:</p>



<pre class="wp-block-code"><code>master
model
msdb
master
tempdb
master
tempdb
model</code></pre>



<p>Query to see connections on SQL Server:</p>



<pre class="wp-block-code"><code>CREATE TABLE #TmpLog
(SPID int, Status VARCHAR(150), Login varchar(100), HostName VARCHAR(150), BlkBy varchar(30), DBName varchar(60), Command varchar(500),
CPUTime int, DiskIO int, LastBatch varchar(20), ProgramName varchar(200), SPID2 int, requestid int)
INSERT INTO #TmpLog
EXEC sp_who2
SELECT SPID, Status, Login, HostName, BlkBy, DBName, Command, ProgramName
FROM #TmpLog
where STATUS not in (‘BACKGROUND’) and Command not in (‘TASK MANAGER’) and ProgramName like ‘.net%’
DROP TABLE #TmpLog
go</code></pre>



<p>Results of running query on SQL Server:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="143" class="wp-image-3435" src="https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1024x143.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1024x143.png 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-300x42.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-768x107.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-1536x214.png 1536w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query-50x7.png 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/02/sql-query.png 2013w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-reduce-connection-pools-hitting-multiple-databases/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Few Errors in SQL Server and How to Fix it</title>
		<link>https://topreviewhostingasp.net/few-errors-in-sql-server-and-how-to-fix-it/</link>
					<comments>https://topreviewhostingasp.net/few-errors-in-sql-server-and-how-to-fix-it/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Wed, 27 Jan 2021 03:33:41 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[error sql server]]></category>
		<category><![CDATA[how to fix sql error]]></category>
		<category><![CDATA[sql error]]></category>
		<category><![CDATA[sql hosting]]></category>
		<category><![CDATA[sql tips]]></category>
		<category><![CDATA[sql tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2873</guid>

					<description><![CDATA[When starting to work with Entity Framework and SQL Server, you often run into the same errors. Sometimes these errors are caused by missing permissions for the database connection, and sometimes it&#8217;s caused the way that the database is accessed. In this article, we will go through some of the most common errors and some [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>When starting to work with Entity Framework and SQL Server, you often run into the same errors. Sometimes these errors are caused by missing permissions for the database connection, and sometimes it&#8217;s caused the way that the database is accessed. In this article, we will go through some of the most common errors and some of the possible ways these errors could be fixed.</p>



<p>In Sql Server, <strong>user accounts and credentials</strong> are set at the server level, not at the database level. When you deploy an SQL database, only the database info moves over. You need to connect to the Database Server in your <strong>deployed environment</strong> , set up the username and password you want to use, and give the account appropriate permissions into the database. So, first you have to make sure that the user exist on <strong>SQL Server</strong> , that the user is enabled, and has access (mapped) to the correct database.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="642" height="359" class="wp-image-2874 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error.jpg 642w, https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error-300x168.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/01/sql-error-50x28.jpg 50w" sizes="(max-width: 642px) 100vw, 642px" /></figure>
</div>



<h2 class="wp-block-heading">How to Fix Login failed for user &#8216;myUsername&#8217;</h2>



<p>At first glance, this seems like it would cover a quite simple error: That the user credentials passed were not valid. This would seem like it could only be a problem with the connection string like a misspelling of the username or password, and that&#8217;s one of the possible causes of the problem. It could also be a problem in the SQL Server like that your user does not have permission to access the database or that the server does not allow SQL Server authentication. The local version of SQL Server has the Server authentication set to Windows Authentication mode by default, which does not enable the possibility to connect without Integrated Security.</p>



<p>The measures one can take to fix the problem are the following:</p>



<ol>
<li>Check that the User Id and Password in the connection string are correct.</li>
<li>Ensure that <code>Integrated Security</code> is set to <code>False</code> in the connection string.</li>
<li>Check that the user is present in <code>Security&gt;Logins</code> in the SQL Server connection in Microsoft SQL Server Management Studio.</li>
<li>Try resetting the password of the user.</li>
<li>Ensure that SQL Server authentication is enabled for the server in <code>Server Properties&gt;Security&gt;Server authentication</code> and then select <code>SQL Server and Windows Authentication mode</code>.</li>
</ol>



<h2 class="wp-block-heading">How to Fix Cannot open database &#8220;myDB&#8221; requested by the login. The login failed.</h2>



<p>The error states that there could not be an established connection to a specific database on the server. This could mean that the specified database in the connection string does not exist or that there was a typo in the connection string.</p>



<p>Possible solutions to the problem could be:</p>



<ol>
<li>Check that there are no typos in the <code>database</code> field in the connection string.</li>
<li>If your project is code-first, ensure that you&#8217;ve called <code>myContext.Database.EnsureCreated()</code> before using your context.</li>
<li>If your project is database-first, check the server if the database is present on the server using Microsoft SQL Server Management Studio.</li>
</ol>



<h2 class="wp-block-heading">How to Fix A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.</h2>



<p>This error states that it was not possible to connect to the specified server. The error often comes together with a long wait time because it wants to make sure that it does not just have a slow connection. A typo could cause the error in the connection string or that the server is configured wrong.</p>



<p>These are some of the ways to troubleshoot the problem:</p>



<ol>
<li>Check that the <code>server</code> field in the connection string is written correctly.</li>
<li>Ensure that remote connection is allowed in Microsoft SQL Server Management Studio in <code>Server Properties&gt;Connection&gt;Remote server connections</code>.</li>
<li>When installing Microsoft SQL Server Management Studio, you also get a program called <code>SQL Server Configuration Manager</code>. This can only be used on the computer that the server is running. In <code>SQL Network Configuration&gt;Protocols for SERVERNAME</code> <code>TCP/IP</code> needs to be enabled for it to be accessed.</li>
</ol>



<h2 class="wp-block-heading" id="microsoftentityframeworkcoredbupdateexception">Microsoft.EntityFrameworkCore.DbUpdateException</h2>



<p>This error covers a lot of different errors. What they all have in common is that Entity Framework failed to save the changes to the database. It is essential to inspect the inner exceptions. It is often just a wrapper around all the <code>System.Data.SqlClient.SqlException</code>&#8216;s that occur when the connection is established.<br />Since the ways to fix these errors are unique to each case, we will list some common causes and how to avoid and fix these errors in general terms.</p>



<p><strong>There have been changes to the models that Entity Framework uses in your project</strong><br />Entity Framework creates all the tables in a database by itself, but when the models in a project start to change, there is a clash between what Entity Framework expects and what&#8217;s actually on the SQL Server. A way to solve this is by using the <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations">Migration feature</a> from Entity Framework when you make changes to your models.</p>



<p><strong>The same SQL Server is used for many projects</strong><br />When a lot of projects use the same database by accident or intentionally, there can be clashes in the naming of tables. This would mean that one project&#8217;s Entity Framework connection would think that its table was made, while the scheme is the one of another project. This can be avoided by using unique database names for different projects.</p>



<p><strong>Duplicate of entries with the same primary key</strong><br />If multiple entries with the same primary key are inserted into a table, then there is a conflict in the database. This can sometimes be solved by doing <code>context.SaveChanges()</code> only once per update and sometimes be avoided by explicitly making foreign keys in one-to-many relations instead of letting Entity Framework handle it.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/few-errors-in-sql-server-and-how-to-fix-it/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
