European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

European SQL 2016 Hosting - HostForLIFE.eu :: SQL QUERY With CONVERT And VARCHAR

clock August 23, 2018 09:05 by author Peter

Yesterday, I faced one problem which I would like to highlight for you. One of my testing users generated RDLC report and he was very shocked to find that his tested email address was truncated when he viewed in the report and in "Export to Excel" functionality.

As this report is working for last 2 to 3 years and it's working for multiple uses, so I thought the following points will help me out.

  • Email address might be wrong for this employee.
  • There must be some substring function which were written in column for Email Address in RDLC report.
  • Debugging the code level whether a substring was used.

But, I was suprised to identify the root cause. For Email address, the code in SQL was written as SELECT CONVERT(VARCHAR, EmailAddress) which was truncating it and giving us the wrong result.

Written some dummy email address for illustration.

If you try out -
select CONVERT( VARCHAR, '987654321.987126515151@abcdef.com')

It will return an output as - "987654321.987126515151@abcdef." , Thus, the maximum lenght is consider here which is 30 characters.
So just for information, always use Convert(Varchar(Max), <ColumnName>) or Convert(Varchar(<size>), <ColumnName>) to get the result correct.
Hope it will help you out .

European SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



SQL Server 2016 Hosting - HostForLIFE.eu :: Contained Database : No Need For Server Level Logins Anymore

clock August 21, 2018 11:06 by author Peter

Starting in SQL Server 2012 and in Azure SQL Database, Microsoft introduced the concept of a contained database. A contained database is a database that is completely un-reliant on the instance of SQL Server that hosts the database including the master database. Theoretically, this makes a database much easier to move between servers (You’ll note the absence of SQL Agent jobs from this post, that’s a different problem.). One of the biggest benefits is that it allows database level authentication, so there is no need to have user logins at Server level.

Contained database now enables us to make a database more portable. I can backup and restore to any instance of SQL Server and the database will carry all its logins with it. There is no longer a need to script out all logins and create those at the server instance level for a user to connect to that restored database. I personally have run into the issue of missing logins at instance level when restoring to another server. In these cases, I have had to go back and script out those logins to apply them to the new instance. You can see how in an emergency where the source server may not be available that not having access to those logins could present a real issue. This is also beneficial for databases that are members of Always On Availability Groups--you don’t have to create logins on each server.

In addition to portability, contained databases allow us to expand the control of login creation to more than just the database administrator or highly-privileged user accounts. Traditional databases require you to create server level roles and server level permissions in order to grant database rights to a user.  With contained databases, you avoid this, database owner and users with an ALTER ANY USER permission can now control access to the database. One drawback is the database user account must be independently created in each database that the user will need which adds a little more maintenance.

Below, I will show you how to enable this option at both the server and database levels. From there, I will show you how to create user logins and what the difference is between traditional (non-contained) login accounts and contained users.

Enable at Server level

Script
EXEC sys.sp_configure N'contained database authentication', N'1' 
GO 
RECONFIGURE WITH OVERRIDE 
GO 

GUI

Enable at database level

Note the word “Partial” in the dropdown and script.

PER MSDN

The contained database feature is currently available only in a partially contained state. A partially contained database is a contained database that allows the use of uncontained features.

Use the sys.dm_db_uncontained_entities and sys.sql_modules (Transact-SQL) view to return information about uncontained objects or features. By determining the containment status of the elements of your database, you can discover what objects or features must be replaced or altered to promote containment.

Script
USE [master] 
GO 
ALTER DATABASE [AdventureWorks2016CTP3] SET CONTAINMENT = PARTIAL WITH NO_WAIT 
GO 


GUI


To Add a User
Below, you will note a few differences in syntax. Traditionally we used the work LOGIN while contained uses USER. Also, note that when adding or changing database permissions, the ALTER statements are very different. Traditional uses ROLE and MEMBER while Contained uses AUTHORIZATION and SCHEMA.

Traditional NON-Contained, adding user and granting READ/WRITE to a database,
CREATE LOGIN JoeShmo WITH PASSWORD = '1234Password'; 
 
USE [AdventureWorks2016CTP3] 
GO 
CREATE USER [JoeShmo] FOR LOGIN [JoeShmo] 
GO 
USE [AdventureWorks2016CTP3] 
GO 
ALTER ROLE [db_datareader] ADD MEMBER [JoeShmo] 
GO 
USE [AdventureWorks2016CTP3] 
GO 
ALTER ROLE [db_datawriter] ADD MEMBER [JoeShmo] 
GO 


Contained Database adding user and granting READ/WRITE to a database -- this works for both SQL Authentication and Windows.
CREATE USER JoeShmo WITH PASSWORD = '1234strong_password'; 
 
USE [AdventureWorks2016CTP3] 
GO 
ALTER AUTHORIZATION ON SCHEMA::[db_datareader] TO [JoeShmo] 
GO 
USE [AdventureWorks2016CTP3] 
GO 
ALTER AUTHORIZATION ON SCHEMA::[db_datawriter] TO [JoeShmo] 
GO 


If changing to Contained database and you want to convert all your Server Logins to contained database users, Microsoft has given us a great script to use. I have reposted it below. The example must be executed in the contained database.
DECLARE @username sysname ;  
DECLARE user_cursor CURSOR  
    FOR   
        SELECT dp.name   
        FROM sys.database_principals AS dp  
        JOIN sys.server_principals AS sp   
        ON dp.sid = sp.sid  
        WHERE dp.authentication_type = 1 AND sp.is_disabled = 0;  
OPEN user_cursor  
FETCH NEXT FROM user_cursor INTO @username  
    WHILE @@FETCH_STATUS = 0  
    BEGIN  
        EXECUTE sp_migrate_user_to_contained   
        @username = @username,  
        @rename = N'keep_name',  
        @disablelogin = N'disable_login';  
    FETCH NEXT FROM user_cursor INTO @username  
    END  
CLOSE user_cursor ;  
DEALLOCATE user_cursor ; 


Aside from the lack of support for MSDB, the one other issue I’ve run into with contained databases was an application that contained multiple databases supporting the applications but used SQL logins. In this case, it was a version of dynamics -- with Windows logins this is easy -- you simply create the login in each database and let Active Directory deal with the passwords. However, with contained databases the passwords are local to each database--so it’s a challenge to sync these accounts. With my current customer in this situation, we’ve reverted to server logins and used Dbatools to sync the passwords between servers. I can think of many ways contained database can add benefits, I can’t wait to play around with it more.

European SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



SQL Server 2016 Hosting - HostForLIFE.eu :: Stuff Function In SQL Server

clock August 16, 2018 09:23 by author Peter

Stuff is a function in SQL Server used to perform special operations on a string value.
The below operations can be performed,

  • Remove string part from string expression.
  • Insert/Append string at specified index.

Syntax
select STUFF(string_value, start_index, no_of_chars_to_replace, replace_string); 

Remove String Part
select STUFF('hai_hello',0,2,''); 

Important Note
Start Index begins from 1 in STUFF Function.

Proper Index
select STUFF('hai_hello',1,2,''); 

Insert String Content
You can insert a string content by specifying the index location and set number of characters to replace to zero. Note that the third parameter value should be zero.
DECLARE @testString varchar(3) = 'abc'; 
select STUFF('hai_hello', 1, 0, @testString); 

Replace String Content
You cannot replace string by specifying the old characters here.
But you can replace the string by specifying start location and number of characters to replace.

Note
The third parameter value should be the length to replace.

Example 1
DECLARE @testString varchar(3) = 'abc'; 
select STUFF('hai_hello', 1, DATALENGTH (@testString), @testString); 

Example 2
select STUFF('hai_hello',1,2,'abc');

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2016 Hosting - HostForLIFE.eu :: How To Replace Newline Character From The SQL Server Field?

clock August 14, 2018 11:41 by author Peter

In this post, we will learn about how to replace newline characters from SQL fields. In this post, we have to use replace function for replace string and also use char function to remove newline characters and replace them. Here I will give you the syntax of replace function, how to use char function, and the meaning of 10 in char function.
Syntax
Description of parameter value,

  • string - Source string
  • string_to_replace - String to search for in string1
  • replacement_string - Replacement string will be replaced string_to_replace with replacement_string in string1

What Char(10) in SQL. Execute the below selected query for checking what char(10) contains. Char(10) displays blank result in SQL query result which means it's \r or \n
SELECT CHAR(10) 

Below query replaces char(10) to html <br /> tag,
REPLACE(EventNote, CHAR(10),'<br />')

See the 4th result in the screenshot for replacing string display with HTML <br /> tag.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



European SQL 2017 Hosting - HostForLIFE.eu :: To Overcome "The Given Key Was Not Present In The Dictionary" Exception In MySQL

clock August 9, 2018 08:37 by author Peter

In this article, I will give one of the solutions to overcome the "The given key was not present in the dictionary" exception in MySQL. Developers may face this error in many situations, but I faced this error in query execution after migrating the MSSQL Database to MySQL.

Recently, I have migrated a database from MSSQL to MySQL. After migration, I tried to run the simple select query with joins which already worked in my application with MSSQL connection string. When I ran the same query with MySQL Connection string, I got the “The given key was not present in the dictionary” Exception. But if I run the same query in MySQL Workbench, it's working fine.

So, here is my sample query which I tried to execute through MySqlDataAdapter.
Select * from usersdetails; 
nMySqlDataAdapter = new MySqlDataAdapter(xszQuery, zSqlConn); 


When this query passes MySqlDataAdapter, I'm getting the exception “The given key was not present in the dictionary”. But the same query is working fine in MySQL Workbench.

It's the same process if I pass the query like,
Select usersID,usersname from usersdetails; 
nMySqlDataAdapter = new MySqlDataAdapter(xszQuery, zSqlConn); //Working fine without any exception. 

I have searched for many solutions on Google, but none worked for me. Some solutions said that error in connection string needs to include the charset=utf8 parameter with the connection string. But that didn't work for me.

Then I found something:
Select usersID,usersname from usersdetails; // this query working fine, no error 
Select usersID,usersname,usersAddress from usersdetails; // this query returns exception 
Select usersID,userGUID from usersdetails; // this query working fine, no error 
Select usersID,userGUID,userDepartment from usersdetails;  // this query returns exception 


So, the problem is something with the columns which I trying to select, then I found what makes each column differ from the other.

What I found is “Collation” value of each column is different based on column datatype, I don’t know in what basis these values are assigned during migration.

What is Collation in MySQL?
A collation is a set of rules that defines how to compare and sort character strings. Each collation in MySQL belongs to a single character set. Every character set has at least one collation, and most have two or more collations.

A collation orders characters based on weights. Each character in a character set maps to a weight. Characters with equal weights compare as equal, and characters with unequal weights compare according to the relative magnitude of their weights.

To know more about “Collation” click here.

I followed two different methods to overcome this exception.

Method 1
By selecting “Table default” value in “Collation” option for the all columns in a table we can overcome this exception.


Method 2
During migration from MSSQL to MySQL, on manual editing step, we can see the tables, column names, and respective datatypes. In the following image on step 3, by default MySQL had taken “CHARACTER SET ‘utf8mb4’ ” as charset value for some columns. We can edit this section, just select and delete “CHARACTER SET ‘utf8mb4’ ” and apply changes. Now all columns with “Collation” value become “Table default” after migration.

By using these two ways we can overcome this exception. In this article, I have given one of the ways to overcome “The given key was not present in the dictionary” exception. If anybody knows any other way to overcome this exception, please mention in the comment  box. I hope this article is very useful.

European SQL 2017 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European SQL 2016 Hosting - HostForLIFE.eu :: Indexes In SQL Server

clock August 7, 2018 09:19 by author Peter

One of the most important routes to high performance in SQL server database is an index. It is a database object which is used to speed up the querying process by providing quick access to rows in the database tables. By using Indexes we can save time and can improve the performance of database queries and applications. An Index contains keys built from one or more columns in the table mapped to the storage location of the specified data. When we create an index on any column, SQL server internally maintains a separate table called index table, so that whenever a user tries to retrieve the data from the existing table,  depending on the index Table SQL server goes directly to the table and retrieves the required data very quickly.

In the Table we can use a maximum of 250 Indexes. The Index Type refers to the way the index is stored internally by SQL server. So a Table can contain two types of indexes:

  • Clustered Index
  • Non-clustered Index

Clustered Indexes
The only time the data rows in a table are stored in sorted (ascending order only) order structure is when the table contains a clustered index. When a table has a clustered index, then it is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure. A table can have only 1 clustered Index on it, which will be created when a primary key constraint is used in a Table.

Non-Clustered Indexes
Non-clustered Indexes will not have any arrangement order (unordered structure) of the data in the table. In a table, we can create 249 non clustered Indexes.If we don't mention clustered indexes in a table then a default is stored as non-clustered Indexes.

European SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in