Wednesday, July 29, 2020

Import data from .sql file to SQL Server database using sqlcmd utility

sqlcmd is a command line utility that is part of the standard installation of SQL Server 2005 or higher, which enables interactive interface with any SQL Server instance to help perform the following tasks:
  1. Execute Transact-SQL (T-SQL) statements in SSMS
  2. Call a T-SQL script file
  3. Use of environment variables in command mode
  4. Store the output results of executed queries in a specified text file

How to use SQLCMD

This utility can be download and install from below link 


Example:

After installation of sqlcmd utility

Step 1. Make a database in you SQL server with student table (id int, name varchar(100))

Step 2. make a TEST.sql script file with below code

           USE TestDB;

           INSERT INTO student (id, name)
           VALUES (1,'Neeraj Gusain')


Step 3. open command prompt and write below line to run mentioned script in .sql

            sqlcmd -S 10.100.0.5\SQLEXPRESS -U sa -P admin@123 -i D:\TEST.sql



sqlcmd is a simple, yet powerful scripting environment that helps with the automation of several tasks related to SQL Server. For example, you can write and execute a script that logs you into a specific instance of SQL Server, executes a script from a specified path, and redirects the output to a certain file.

Most of us SQL database administrators are already using PowerShell. The Invoke-SqlCmd cmdlet, from the sqlserver module that’s part of every SQL Server distribution since 2008, packs most of the capabilities of sqlcmd. Also, in SQL Server Management Studio, we have a SQLCMD mode, that simulates the capabilities of sqlcmd, and accepts some of the commands that are not part of the T-SQL language.

sqlcmd was an extension of the osql and isql command line utilities, that contains a rich set of parameters and options to enable automation of various administrative tasks.

  1. It’s simple to bind SQL in a .bat file.
  2. It runs interactively across various OS platforms.
  3. It’s easy to pass command line arguments to a SQL file using sqlcmd.

How to enable SQLCMD

OK, so sqlcmd is a great tool; of that, we’re all convinced. Let’s now talk about how the query editor in SSMS can be used to write statements as sqlcmd scripts. The following example talks about the integration of Windows system commands and T-SQL statements into a single script.

It’s importatnt to remember that sqlcmd mode is not enabled by default. To enter into the sqlcmd mode in the SSMS query editor, follow the steps below:

  1. In the Object Explorer right click the SQL Server and then click New Query
    OR
    Open a new Database Engine Query Editor window.
  2. On the Query editor, click SQLCMD Mode.

To enable SQLCMD scripting mode:

  1. On the SSMS, go to the Tools menu, select Options.
  2. Expand the Query Execution tab, and select SQL Server, click the General page.
  3. Check the box against By default open new queries in SQLCMD Mode.

Some important points to remember
  1. SQLCMD commands must be prefixed with a colon. This makes the difference between SQLCMD commands and Transact-SQL clear.
  2. The :CONNECT keyword is used to connect to a different server using the same session context.
  3. The Operating system commands (in this case, if exists) and del commands used for the demo must start with two exclamation points (!!). The !! indicate that the commands are OS command, which will be executed using the cmd.exe command processor. In this example, the OS command, if exist $(file1) del $(file1) is passed as arguments to cmd.exe.
  4. The variables that are used as part of the SQLCMD script are case-sensitive. For example, if we query the environment variables, we can see that COMPUTERNAME and computername are two different variables in the output. In the first, the environment variable is queried to return the name of the computer, where as in the second, SSMS isn’t able to resolve the variable and reports an error.

Examples of SQLCMD

The following example defines an integration of operating system commands and SQL statements together.

Variable are defined using SETVAR, connection is built using CONNECT the keyword, operating system commands are defined using !!, the output file is declared using the OUT keyword, and SQL Statements are placed to fetch the results based on the connection string.

SQLCMD with scripting variables, and Windows scripting in SSMS

In this example, login is created across multiple servers. T-SQL, sqlcmd and Windows scripting are all integrated, and run using the SSMS interface to create logins.

  1. Enable XP_CMDSHELL
  2. Define the T-SQL in a SQL file
  3. Build the dynamic SQL
  4. Verify the output

STEP 1: In this step, xp_cmdshell is enabled. It is not a recommended option, though. This has only been enabled for the purpose of the demo.

STEP 2: A SQL file, SysAdminLoginCreation.sql is created with the create login SQL statement.

The file looks like below

We create a for loop to loop through each SQL instances.

  1. Iterate through the input file.
  2. FOR Parameter %j defines the name of the SQL instance.
  3. Call sqlcmd using the parameters as part of the command.
  4. Repeat for each data item.

sqlcmd executed successfully!

Let’s check whether the logins are created on the those servers

The logins have also been created for the listed servers.

Passing variables (or argument) as T-SQL and SQL Script file

We can pass the variables as an input to the T-SQL or the SQL script file in the sqlcmd command console. The scripting variables are declared using :SETVAR keyword. The corresponding parameter values passed to T-SQL or SQL script file. The values are enclosed in $(variable name) are fed to the SQLs during the run time. Using -v (version) switch, the parameters are declared and fed to the script. We can list any number of variables with no delimiter in between the parameters. Lets follow the example to understand the mechanism better:

  1. The salesorderdetails is the name of table assigned to tablename variable
  2. The select statement is prepared along with the tablename variable

We can assume that database name will be provided as a SQLCMD variable during the deployment process; we can have exactly the same file deployed to all environments. The following example has two parameters, db and tablename. The input parameters are separated by a space in between.

Summary

Thursday, July 23, 2020

How to implement MERGE statement in SQL Server

SQL Server provides the MERGE statement that allows you to perform three actions (INSERT/UPDATE/DELETE) at the same time. 

The following shows the syntax of the MERGE statement:

MERGE target_table USING source_table ON merge_condition WHEN MATCHED THEN update_statement WHEN NOT MATCHED THEN insert_statement WHEN NOT MATCHED BY SOURCE THEN DELETE;

To implement MERGE Statement, if you run the below example, you can easily learn this concept.

DECLARE  @category AS TABLE (
    category_id INT PRIMARY KEY,
    category_name VARCHAR(255) NOT NULL,
    amount DECIMAL(10 , 2 )
);

INSERT INTO @category(category_id, category_name, amount)
VALUES(1,'Children Bicycles',15000),
    (2,'Comfort Bicycles',25000),
    (3,'Cruisers Bicycles',13000),
    (4,'Cyclocross Bicycles',10000);


DECLARE  @category_staging AS TABLE(
    category_id INT PRIMARY KEY,
    category_name VARCHAR(255) NOT NULL,
    amount DECIMAL(10 , 2 )
);


INSERT INTO @category_staging(category_id, category_name, amount)
VALUES(1,'Children Bicycles',15000),
    (3,'Cruisers Bicycles',13000),
    (4,'Cyclocross Bicycles',20000),
    (5,'Electric Bikes',10000),
    (6,'Mountain Bikes',10000);

SELECT * FROM @category
SELECT * FROM @category_staging


MERGE @category t 
USING @category_staging s
ON (s.category_id = t.category_id)
WHEN MATCHED
    THEN UPDATE SET 
        t.category_name = s.category_name,
        t.amount = s.amount
WHEN NOT MATCHED BY TARGET 
    THEN INSERT (category_id, category_name, amount)
         VALUES (s.category_id, s.category_name, s.amount)
WHEN NOT MATCHED BY SOURCE 
    THEN DELETE
;

SELECT * FROM @category

Thursday, July 9, 2020

How to create and configure a linked server to connect to MySQL in SQL Server Management Studio

Create a linked server in SSMS to connect to the MySQL database.
This article is divided in three sections:
  • Installing ODBC driver for MySQL
  • Configure ODBC driver to connect to MySQL database
  • Create and configure a Linked Server using ODBC driver

Installing ODBC driver for MySQL

ODBC stands for Open Database Connectivity (Connector). It’s developed by Microsoft in the 1990s. Generally, that is API (Application Programming Interface) for accessing database systems.
For non-Windows OS, JDBC (Java Database Connectivity) is used.
Before installing the ODBC driver for MySQL on Windows, make sure that Microsoft Data Access Components (MDAC) are up to date and the Microsoft Visual C++ 2013 Redistributable Package is installed on your system.
Under this link, the MySQL ODBC drivers for Windows can be downloaded and installed. There are two versions of MySQL ODBC drivers for Windows that can be installed, depending on which application will be used with:
MySQL Connection/ODBC for Windows
  • mysql-connector-odbc-8.0.17-win32.msi for 32-bit application
  • mysql-connector-odbc-8.0.17-winx64.msi for 64-bit application
Installation of MySQL ODBC driver for Windows is straightforward. Double-click on the downloaded file, the Welcome dialog will appear:
MySQL Connection/ODBC wizard - Welcome dialog
After pressing the Next button, the License Agreement dialog appears. If you agree with the license agreement, press the I accept the terms in the license agreement radio button and click the Next button:
MySQL Connection/ODBC wizard - License Agreement dialog
Under the Setup Type dialog, choose the Typical radio button and press the Next button:
MySQL Connection/ODBC wizard - Setup Type dialog
The Ready to Install the Program dialog shows what and where will be installed. Press the Install button to install ODBC driver:
MySQL Connection/ODBC wizard -Ready to Install the Program dialog
After a couple of seconds, installation of ODBC driver for MySQL is finished:
MySQL Connection/ODBC wizard - Wizard Completed dialog
To confirm that ODBC driver for MySQL is installed on machine can be checked from Control Panel:
Check is it the ODBC driver for MySQL installed on machine via Control Panel
Another way to check is via the ODBC Data Source Administrator dialog box:
Check is it the ODBC driver for MySQL installed on machine via ODBC Data Source Administrator
Under the Drivers tab of the ODBC Data Source Administrator dialog box, check if the MySQL ODBC Drivers exist:
Check is it the ODBC driver for MySQL installed on machine via ODBC Data Source Administrator and Drivers tab

Configure ODBC driver to connect to MySQL database

To connect to MySQL database using ODBC drivers, in the ODBC Data Source Administrator dialog, under the System DSN tab, press the Add button:
System DSN tab of the ODBC Data Source Administrator dialog
In the Create New Data Source dialog, select the MySQL ODBC Driver and press the Finish button:
Create New Data Source to connect to MySQL
In the MySQL Connector/ODBC Data Source Configuration dialog:
Connector/ODBC configuration dialog to connect to MySQL database
For the Data Source Name text box, enter the data source name by choice. In the Description text box, enter the description of the data source if needed.
Use the TCP/IP Server or Named Pipe connection method to connect to MySQL by selecting appropriate radio button.
In this example, the TCP/IP Server radio button is selected. In the text box, type a host name or IP address of the MySQL server. By default, the host name is localhost and IP address is 127.0.0.1. In the Port box, enter the TCP/IP port on which the MySQL server is listed. By default, it is 3306 port.
In the User box, type the name of the user needed to connect to the MySQL database and, in the Password box, type a user password. Under the Database combo box, choose the database for which want to establish connection:
Connector/ODBC connection parameters to connect to MySQL database
To test if it is connected to MySQL database configured correctly, press the Test button. The following message will appear if the connection is established successfully:
Connect to MySQL database established succesfully
Also, the data source name will appear in the System DSN tab of the ODBC Data Source Administrator dialog:
Newly created data source name in the System DSN tab of the ODBC Data Source Administrator dialog

Create and configure a Linked Server using ODBC driver

Now, when the ODBC driver for MySQL has been installed and ODBC driver to connect to MySQL database has been configured, configuring Linked Server in SSMS to connect to MySQL can begin.
Go to SSMS, in Object Explorer, under the Server Objects folder, right-click on the Linked Servers folder and, from the menu, select the New Linked Server option:
Context menu to create a linked server
The New Linked Server dialog will appear. Here will be entered configuration to connect to MySQL server:
The New Linked Server dialog
In the Linked server text box of the General tab, enter the name of how the linked server will be called (e.g. MYSQL_SERVER).
Choose the Other data source radio button and from the Provider list, choose the Microsoft OLE DB Provider for ODBC Drivers item:
The New Linked Server dialog  - ODBC Drivers
Under the Product name box, enter any appropriate (valid) name. For the Data source, it should be entered the name of ODBC data source:
The New Linked Server dialog  - ODBC Data source
In the Security tab, click the Be made using this security context radio button and in the Remote login and With password boxes, enter the user name and password that exist in the MySQL server instance, that is chosen as data source:
The New Linked Server dialog  - Security tab
Under the Server Options tab, set the RPC and RPC Out fields to True:
The New Linked Server dialog  -Server Options tab
In case when these two options are not set to true and execute a code like this:
The following error may appear:
Msg 7411, Level 16, State 1, Line 1
Server ‘MYSQL_SERVER’ is not configured for RPC.
More about options under the Security and Server Options tabs can be found on the How to create and configure a linked server in SQL Server Management Studio page.
After all options under the New Linked Server dialog are set, press the OK button. Newly created linked server should appear in the Linked Servers folder:
MySQL linked server
Before start to querying data from MySQL database, go to the Providers folder under the Linked Server folder, right-click on the MSDASQL provider and, from the context menu, choose the Properties command:
MSDASQL provider
In the Provider Options dialog, check the Nested queries, Level zero only, Allow in process, Support ‘Like’ operator check boxes:
Provider Options dialog
For example, if the Allow in process check box is not checked, when executing code like this:
The following error message may appear:

Msg 7399, Level 16, State 1, Line 1
The OLE DB provider “MSDASQL” for linked server “MYSQL_SERVER” reported an error. Access denied.
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider “MSDASQL” for linked server “MYSQL_SERVER”.

The linked Server can also be made by using TSQL scripts:

EXEC master.dbo.sp_addlinkedserver
@server=N'MySQL',
@srvproduct=N'MySQL',
@provider= N'MSDASQL',
@datasrc= N'MySQL',
@provstr=N'DRIVER={MySQL ODBC 8.0 ANSI Driver};SERVER=localost;PORT=3306;DATABASE=healthcare;USER=root;PASSWORD=123464;OPTION=3;'

EXEC master.dbo.sp_addlinkedsrvlogin   
@rmtsrvname = N'MySQL',
@locallogin = NULL,
@rmtuser = N'root',

@rmtpassword= N'123456'

If is there is any error , then RUN below script in MYSQL to give permission to root user.
grant all on *.* to root@localhost

refer below link for more 
https://www.sqlshack.com/create-configure-drop-sql-server-linked-server-using-transact-sql/

Truncating Data in SQL Server and fixed in ANSI_WARNINGS


Here in SQL SERVER 2019, 
Microsoft has fixed one of our old age problem about displaying the column which is being truncated while inserting the data i.e. "String or binary data would be truncated" by the help of ANSI_WARNINGS

Let's check it with an example.

First, create a test table with a single column with datatype varchar(5).
1
2  
3
 USE Test_Data
GO
CREATE TABLE ProductTable (ProductName VARCHAR(5));


Next, try to insert data string which is longer than 5 characters.
1
2
3
  INSERT INTO ProductTable (ProductName)
  VALUES ('Samsung Mobile');
  GO

When you run the above script it will give you the following error:

Msg 2628, Level 16, State 1, Line 1
String or binary data would be truncated in table ‘TestData.dbo.ProductTable’, column ‘ProductName’. Truncated value: ‘Samsu’.
The statement has been terminated.

This is because the string is larger than the maximum width the column can hold. Now let us run a simple select statement and see the data inside the table. You will find that your table is empty and there are no data in it.

While we were working with various options, we turned off the ANSI_WARNINGS for the session and when we ran the same command, the result was interesting. Let us try that out together.

Turn off the ANSI warnings.

1  
2
SET ANSI_WARNINGS OFF
GO

Next, run the following command one more time.
1
2
3
  INSERT INTO ProductTable (ProductName)
  VALUES ('Samsung Mobile');
  GO

Now this time the query will work fine and there will be no error at all.

 


Tuesday, July 7, 2020

Turning OFF or ON Query Store for All the Database in SQL Server



----// Turning OFF Query Store for All the Databases

SELECT 'USE master;' AS Script
UNION ALL
SELECT 'ALTER DATABASE ['+name+'] SET QUERY_STORE = OFF;'
FROM sys.databases
WHERE name NOT IN ('master', 'model', 'tempdb', 'msdb', 'Resource')
AND is_query_store_on = 1;

----// Turning ON Query Store for All the Databases

SELECT 'USE master;' AS Script
UNION ALL
SELECT 'ALTER DATABASE ['+name+'] SET QUERY_STORE = ON;'
FROM sys.databases
WHERE name NOT IN ('master', 'model', 'tempdb', 'msdb', 'Resource')
AND is_query_store_on = 0;


----// Query Store for All the Databases For Operation Mode = Read Write

SELECT 'USE master;' AS Script
UNION ALL
SELECT 'ALTER DATABASE ['+name+'] SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE);'
FROM sys.databases
WHERE name NOT IN ('master', 'model', 'tempdb', 'msdb', 'Resource')
AND is_query_store_on = 0;

----// Query Store for All the Databases For Operation Mode = Read Only

SELECT 'USE master;' AS Script
UNION ALL
SELECT 'ALTER DATABASE ['+name+'] SET QUERY_STORE = ON (OPERATION_MODE = READ_ONLY);'
FROM sys.databases
WHERE name NOT IN ('master', 'model', 'tempdb', 'msdb', 'Resource')
AND is_query_store_on = 0;

----// Read-Only Database

-- Script to make database read only 
USE [master]
GO
ALTER DATABASE [TestDb] SET READ_ONLY WITH NO_WAIT
GO

----// Read Write Database

-- Script to make database read write
USE [master]
GO
ALTER DATABASE [TestDb] SET READ_WRITE WITH NO_WAIT

GO