European Windows 2019 Hosting BLOG

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

SQL Server Hosting - HostForLIFE :: DDL, DQL, DML, DCL, TCL with Examples

clock March 16, 2022 09:04 by author Peter

In this article, you will learn the SQL command categories and their sub-categories. SQL is an open-source data management system. The SQL query is used to retrieve and manipulate the data from the table. With the help of SQL command we can query, filter, sort, join, group and modify the data in the database.
SQL Commands

SQL commands are categorized into below 5 categories:

  • DDL – Data Definition Language
  • DQL – Data Query Language
  • DML – Data Manipulation Language
  • DCL – Data Control Language
  • TCL - Transaction Control Language

DDL (Data Definition Language)
DDL or Data definition language is actually the definition or description of the database structure or schema, it won't change the data inside the database. Create, modify, and delete the database structures, but not the data. Only These commands are not done by all the users, who have access to the database via an application.

CREATE
Create the database or its object (ie table, index, view, function etc.).

CREATE DATABASE databasename

Example
CREATE DATABASE Student_data;

Syntax
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);

Example
CREATE TABLE Student (
   StudendId int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    Mark int
);


DROP
Drop command helps to delete the object from the database (ie table, index, view, function, etc.).
DROP object object_name

Example
DROP TABLE Student;

DROP DATABASE database_name

Example
DROP DATABASE Student_data;

ALTER
Alter command is helpful to change or modify the structure of the database or its object.
ALTER TABLE table_name
ADD column_name datatype


Example
ALTER TABLE Student
ADD Total int;


ALTER TABLE table_name
DROP COLUMN column_name


Example
​​​​​​​ALTER TABLE Student
DROP COLUMN Mark;


1) SQL Server / MS Access
ALTER TABLE table_name
ALTER COLUMN column_name datatype


Example
ALTER TABLE Student
ALTER COLUMN Total Varchar(255);


2) My SQL / Oracle (prior version 10G)
ALTER TABLE table_name
MODIFY COLUMN column_name datatype


Example
ALTER TABLE Student
MODIFY COLUMN Total Varchar(255);


3) Oracle 10G and later
ALTER TABLE table_name
MODIFY column_name datatype


Example
​​​​​​​ALTER TABLE Student
MODIFY Total Varchar(255);


TRUNCATE
Truncate command helps to remove all records from a table.
TRUNCATE TABLE  table_name


Example
TRUNCATE TABLE  Student;

COMMENT
Comment is helpful to add comments to the data dictionary."--" is used to comment the notes.
--(notes,examples)

Example
--select the student data
SELECT * FROM Student;


RENAME

Rename is helpful to rename an object existing in the database.
1) PostgreSQL
ALTER DATABASE "Old_DatabaseName" RENAME TO "New_DatabaseName";

Example
ALTER DATABASE "Student_data" RENAME TO "Employee_data";

2) MySQL
Example
SQL Command for Dump copy
mysqldump -u username -p"password" -R testDb > testDb.sql;

SQL Command for creating new DB
mysqladmin -u username -p"password" create testDB1;

SQL Command for Import
mysql -u username -p"password" testDb1 < testDb.sql;

Also for Unix, database names are case-sensitive

3) SQL Server
In SQL Server we can rename the database through server application, by right click the existing database and renaming it.

DQL (Data Query Language)
DQL or data query language is to perform the query on the data inside the schema or object (ie table, index, view, function, etc). With the help of DQL query we can get the data from the database to perform actions or operations like analysing the data.

SELECT
Select query on a table or tables to view the temporary table output from the database.
Select * from Table_Name;

Example
Select * from Student;

DML(Data Manipulation Language)
DML or Data Manipulation Language is to manipulate the data inside the database. With the help of DML commands, we can insert, delete, change the data inside the database.

INSERT
Insert command is helpful to insert the data into a table.

1) All the column names are mentioned in the insert statement.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...)


Example
INSERT INTO Student (StudendId, FirstName, LastName)
VALUES (12345, "Sri", "Durga");

2) Column names do not need to mentioned in the query, Values should be given in the order according to the column.
INSERT INTO table_name
VALUES (value1, value2, value3, ...)

Example
INSERT INTO Student
VALUES (12345, "Anna", "Marry");

UPDATE
Update command is helpful to update the existing data in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition


Example
UPDATE Student
SET FirstName = "Peter" , LastName = "Scott"
WHERE StudentId=12345;


DELETE
Delete command helps to delete the records from a database table.

Syntax
DELETE FROM table_name WHERE condition;

Example
DELETE FROM Student WHERE StudentId=12345;

LOCK
Lock command is helpful to lock the table to control concurrency.
LOCK TABLE table-Name IN { SHARE | EXCLUSIVE } MODE

Example
LOCK TABLE Student IN SHARE MODE;

CALL
Call command is helping to Call a PL/SQL or JAVA subprogram.
EXEC SQL
 CALL GETEMPSVR (2, NULL)
END-EXEC


EXPLAIN PLAN
It describes the access path to the data.
EXPLAIN PLAN FOR
SELECT Column_name FROM table_name


Example
EXPLAIN PLAN FOR
SELECT last_name FROM Student;


SQL
This query explanation will be stored in the PLAN_TABLE table. We can then select the execution plan to review the queries.
DCL (Data Control Language)

DCL or Data Control Language is to provide rights, permissions, and other controls of the database system.

GRANT
GRANT command is helpful to provide privileges to the database.
GRANT privileges_names ON object TO user

Example
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Name'@'localhost;
GRANT ALL ON Users TO 'Name'@'localhost;
GRANT SELECT  ON Users TO '*'@'localhost;


GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user

REVOKE
Revoke command is to withdraw the user’s access privileges given by using the GRANT command.

REVOKE privileges ON object FROM user

Example
REVOKE SELECT, INSERT, DELETE, UPDATE ON Users TO 'Name'@'localhost;

REVOKE ALL ON Users TO 'Name'@'localhost;

REVOKE SELECT  ON Users TO '*'@'localhost;

REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user
TCL (Transaction Control Language)


TCL or Transaction Control Language happens to a transaction in the database.

COMMIT
Commit command is to commit Transaction after insert or delete in the database.
Commit;

Example
DELETE from Student where Student_Id = 12345;
COMMIT;

ROLLBACK
Rollback command is to rollback a transaction in case of any error occurs.
Rollback;

Example
DELETE from Student where Student_Id = 12345;
ROLLBACK;


SAVEPOINT
Savepoint command is to Set a savepoint within a transaction. If transaction happens in big data, then for checking and rollup can't do it with all the data, to rollback the small part of the data we use savepoint query.

SAVEPOINT savepoint_name

SET TRANSACTION
Set command is to Specify the characteristics of the transaction.

SET TRANSACTION Access NAME transaction_name



SQL Server Hosting - HostForLIFE :: Convert SQL Server Data to JSON

clock March 9, 2022 07:31 by author Peter

In this article, let’s learn how to convert SQL Server data to JSON format. JSON format has become a standard way to represent data objects into strings. JSON format is commonly used in APIs to trasfer data from one application to other via APIs.

You can convert a SQL query results in JSON format in SQL Server by simply adding FOR JASON clause to the query. FOR JASON is used with PATH and AUTO
SELECT name, surname
FROM emp
FOR JSON AUTO;

Here is a simple SQL query on Northwind database that returns 10 orders from the Orders table.
SELECT TOP (10) [OrderID]
      ,[OrderDate]
      ,[ShipName]
      ,[ShipAddress]
      ,[ShipCity]
      ,[ShipPostalCode]
      ,[ShipCountry]
  FROM [Northwind].[dbo].[Orders]

The output in SSMS looks like this.

Now, let’s add FOR JASON PATH clause at the end of the SQL query.
SELECT TOP (10) [OrderID]
      ,[OrderDate]
      ,[ShipName]
      ,[ShipAddress]
      ,[ShipCity]
      ,[ShipPostalCode]
      ,[ShipCountry]
  FROM [Northwind].[dbo].[Orders]
  FOR JSON PATH;


The new output looks like this that is a JSON object.
[{"OrderID":10248,"OrderDate":"1996-07-04T00:00:00","ShipName":"Vins et alcools Chevalier","ShipAddress":"59 rue de l'Abbaye","ShipCity":"Reims","ShipPostalCode":"51100","ShipCountry":"France"},{"OrderID":10249,"OrderDate":"1996-07-05T00:00:00","ShipName":"Toms Spezialitäten","ShipAddress":"Luisenstr. 48","ShipCity":"Münster","ShipPostalCode":"44087","ShipCountry":"Germany"},{"OrderID":10250,"OrderDate":"1996-07-08T00:00:00","ShipName":"Hanari Carnes","ShipAddress":"Rua do Paço, 67","ShipCity":"Rio de Janeiro","ShipPostalCode":"05454-876","ShipCountry":"Brazil"},{"OrderID":10251,"OrderDate":"1996-07-08T00:00:00","ShipName":"Victuailles en stock","ShipAddress":"2, rue du Commerce","ShipCity":"Lyon","ShipPostalCode":"69004","ShipCountry":"France"},{"OrderID":10252,"OrderDate":"1996-07-09T00:00:00","ShipName":"Suprêmes délices","ShipAddress":"Boulevard Tirou, 255","ShipCity":"Charleroi","ShipPostalCode":"B-6000","ShipCountry":"Belgium"},{"OrderID":10253,"OrderDate":"1996-07-10T00:00:00","ShipName":"Hanari Carnes","ShipAddress":"Rua do Paço, 67","ShipCity":"Rio de Janeiro","ShipPostalCode":"05454-876","ShipCountry":"Brazil"},{"OrderID":10254,"OrderDate":"1996-07-11T00:00:00","ShipName":"Chop-suey Chinese","ShipAddress":"Hauptstr. 31","ShipCity":"Bern","ShipPostalCode":"3012","ShipCountry":"Switzerland"},{"OrderID":10255,"OrderDate":"1996-07-12T00:00:00","ShipName":"Richter Supermarkt","ShipAddress":"Starenweg 5","ShipCity":"Genève","ShipPostalCode":"1204","ShipCountry":"Switzerland"},{"OrderID":10256,"OrderDate":"1996-07-15T00:00:00","ShipName":"Wellington Importadora","ShipAddress":"Rua do Mercado, 12","ShipCity":"Resende","ShipPostalCode":"08737-363","ShipCountry":"Brazil"},{"OrderID":10257,"OrderDate":"1996-07-16T00:00:00","ShipName":"HILARION-Abastos","ShipAddress":"Carrera 22 con Ave. Carlos Soublette #8-35","ShipCity":"San Cristóbal","ShipPostalCode":"5022","ShipCountry":"Venezuela"}]

Now, you can use this same return value from SQL query in your application to read JSON objects in your code.

Using the same method, you can convert a SQL Server Table to JSON by using a SELECT * or SELECT column names query on the entire table. The following SQL query converts all rows of a SQL Server table to a JSON string.
SELECT [OrderID]
      ,[OrderDate]
      ,[ShipName]
      ,[ShipAddress]
      ,[ShipCity]
      ,[ShipPostalCode]
      ,[ShipCountry]
  FROM [Northwind].[dbo].[Orders]
  FOR JSON PATH;


Here is a detailed article on JSON in SQL Server with various options.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: SSIS Expression - Convert Date To String

clock March 8, 2022 07:47 by author Peter

SQL Server Integration Services (SSIS) is a component of the Microsoft SQL Server database software that can be used to perform a broad range of data migration tasks. SQL Server Integration Services (SSIS) expressions can help make SSIS packages more dynamic.

In general, expressions in SSIS is a combination of literals, functions, operators that yields a single data value.

An expression can be composed of a single value (“abc”) or a variable (@[User::FilePath]) or a function (GETDATE()), or it can be more complex and contains some conditionals (CASE statement) or some mathematical operations or some string manipulation.

Here I am describing how we can convert the datetime into string with SSIS expression.

There are multiple ways to convert date to string. The two ways are listed below.
(DT_WSTR, 4)(YEAR(@[User::PositionDateToProcess])) + "-"+
(DT_WSTR, 2)(MONTH(@[User::PositionDateToProcess])) +"-"+
(DT_WSTR, 2)(DAY(@[User::PositionDateToProcess]))


2. SUBSTRING((DT_STR,30, 1252) GETDATE(), 1, 10)

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: Create New Database From Existing Database In Same Microsoft SQL Server

clock February 18, 2022 06:50 by author Peter

In this article, we will learn about how to create a new database with the help of an existing database in same Microsoft SQL Server through the help of Procedure in Local Database.

In this article, I explain the process to create the procedure by two methods.

    HardCode
    Dynamically

The below code is of Stored Procedure for creating New Copy Database with New Name in the same server,
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_post_new_database]
     (
   @DatabaseName varchar(100) = 'CopyDatabase',  --Name of New Database which we going to create
   @CopyDatabase varchar(100) = 'OriginalDatabase'    --Name of Database
)
AS
BEGIN
DECLARE  @BackupDataFileNameAndPath VARCHAR(MAX)=''
DECLARE  @OpenDataFileNameAndPath VARCHAR(MAX)=''
DECLARE  @PathBackUpDatabase VARCHAR(MAX) = 'D:\db\'  -- We also make it dynamic ,for dynamic we need pass parameter to Our Store Procedure
DECLARE  @OpenPathDatabase VARCHAR(MAX) = 'D:/db/' -- We also make it dynamic ,for dynamic we need pass parameter to Our Store Procedure
DECLARE  @fileExtenion_mdf VARCHAR(MAX)=''
DECLARE  @fileExtenion_ldf VARCHAR(MAX)=''
DECLARE  @Open_ldf VARCHAR(MAX)=''
SET @BackupDataFileNameAndPath = @PathBackUpDatabase+@DatabaseName+'.bak'  --for dynamic  | for HardCode --> 'D:\db\CopyDatabase.bak'
--Open BackUpdataBase
SET @OpenDataFileNameAndPath = @OpenPathDatabase+@DatabaseName+'.bak'   --for dynamic
SET @fileExtenion_mdf=@PathBackUpDatabase+@DatabaseName+'_Data.mdf' --for dynamic   | for HardCode -->  'D:\db\CopyDatabase_Data.mdf'
SET @fileExtenion_ldf=@PathBackUpDatabase+@DatabaseName+'_Log.ldf'  --for dynamic   | for HardCode -->  'D:\db\CopyDatabase_Data_Log.ldf'
SET @Open_ldf=@CopyDatabase+'_Log'  --for dynamic
--BackUp Our database which name of Our New Created Database
BACKUP DATABASE @CopyDatabase  -- <- for dynamic | for HardCode -->  BACKUP DATABASE 'OriginalDatabase'
   TO DISK =@BackupDataFileNameAndPath    -- <- for dynamic | for HardCode -->  TO DISK = 'D:\db\CopyDatabase.bak'
   WITH FORMAT,
      MEDIANAME = 'MyServerDatabaseBackups',
      NAME = 'Full Backup of My  OriginalDatabase';
  --Used for View the Name Of .mdf and .ldf which are in CopyDatabase.bak
   RESTORE FILELISTONLY
   FROM disk =@OpenDataFileNameAndPath;    -- <- for dynamic | for HardCode -->  FROM disk ='D:/db/CopyDatabase.bak';
-- Restore the files for BackupDataBase.
RESTORE DATABASE @DatabaseName
   FROM disk=@OpenDataFileNameAndPath   -- <- for dynamic | for HardCode -->  FROM disk='D:/db/CopyDatabase.bak'
   WITH RECOVERY,
   -- Below two line Move .mdf and .ldf file from  CopyDatabase.bak and restore in Your Server with
   --Our Given new Database name and Your Desire location in You local Disk
   MOVE @CopyDatabase TO @fileExtenion_mdf,  -- <- for dynamic | for HardCode -->    MOVE 'OriginalDatabase' TO 'D:\db\CopyDatabase_Data.mdf' ,
   MOVE @Open_ldf TO @fileExtenion_ldf;    -- <- for dynamic | for HardCode -->     MOVE 'OriginalDatabase_Log' TO 'D:\db\CopyDatabase_Data_Log.ldf' ;
   --For Delete .bak File From Disk
   --Create BackUp Device "sp_addumpdevice" Procedure set Path of Our CopyDatabase.bak file for delete
   EXEC sp_addumpdevice 'disk', @CopyDatabase, @BackupDataFileNameAndPath ;   -- <- for dynamic | for HardCode -->  EXEC sp_addumpdevice 'disk', 'OriginalDatabase','D:\db\CopyDatabase.bak' ;
   --"sp_dropdevice" Procedure  delete CopyDatabase.bak file from our Local Disk because we already restore new created database in Server
   EXEC sp_dropdevice @CopyDatabase, 'delfile' ;    -- <- for dynamic | for HardCode -->  EXEC sp_dropdevice 'OriginalDatabase', 'delfile' ;
END
GO

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: SQL IS NULL And IS NOT NULL Operators

clock February 15, 2022 07:22 by author Peter

When dealing with NULLs, most beginners think it has some value, but it means unknown.

This article will explore what's NULL is and SQL's NULL conditional operators.

These operators are IS NULL and IS NOT NULL.

What is NULL?

It is used to specify that a particular data value does not exist.

That's why you'll hear from other SQL developers or administrators; NULL represents a missing or unknown value. And from that statement, I think it can be easily remembered and understood.

Moreover, the ANSI behavior for NULL values any expression containing a NULL value is NULL.

Let's see some examples below.
Examples

1. Let's try to add a number to a NULL value.
SELECT (NULL + 1) [Sum of NULL and 1] -- NULL

Output

2. Let's try to concatenate a string to a NULL value.
SELECT (NULL + 'C# Corner Rocks') [Concat NULL to a word] -- NULL

IS NULL and IS NOT NULL
I still remember learning TSQL when I wanted to check a column for NULL. I used the equal (=) or the not (<>) operator.

Let's see an example below.
SELECT * FROM [tblSomething] WHERE name = NULL
SELECT * FROM [tblSomething] WHERE name <> NULL

Note: the example code above won't be behaving as expected. You won't see any results!

Checking for NULL values is impossible with comparison operators such as =, < or <>.

It is because this is not the default behavior of it.

That's why instead of using these equal and or not operators, we can use IS NULL or IS NOT NULL instead.

Let's see an example below.

DROP TABLE IF EXISTS temp.dbo.#tempFruits;

CREATE TABLE #tempFruits
(Id INT IDENTITY,
 [Name] NVARCHAR(10) NOT NULL,
 [Description] NVARCHAR(50) NULL);

 INSERT INTO #tempFruits (Name, Description)
 VALUES
 ('Apple', 'The domesticated tree Malus'),
 ('Kiwifruit', NULL),
 ('Pineapple', NULL),
 ('Papaya', 'Also called papaw or pawpaw'),
 ('Cherry', NULL)

 SELECT * FROM #tempFruits WHERE [Description] = NULL -- 0 result
 SELECT * FROM #tempFruits WHERE [Description] IS NULL -- 3 results

 SELECT * FROM #tempFruits WHERE [Description] <> NULL -- 0 result
 SELECT * FROM #tempFruits WHERE [Description] IS NOT NULL -- 2 results


As you can see, in our code sample above, we have combined the equal and the not operator with their NULL operators' counterparts.

Let's try to see the differences.

First, instead of = operator, we used the IS NULL operator to check whether a column is NULL.
SELECT * FROM #tempFruits WHERE [Description] = NULL -- 0 result
SELECT * FROM #tempFruits WHERE [Description] IS NULL -- 3 results


Output

Second, instead of the <> operator, we used the IS NOT NULL operator to check whether a column is not NULL.
SELECT * FROM #tempFruits WHERE [Description] <> NULL -- 0 result
SELECT * FROM #tempFruits WHERE [Description] IS NOT NULL -- 2 results


Output

SET ANSI_NULLS ON or OFF
Hopefully, now you understand that by default, you can't use the equality operators when dealing with NULLs and instead use IS NULL or IS NOT NULL operators.

However, this default ANSI behavior can be turned off by adding this line of instruction SET ANSI_NULLS OFF before executing the previous entire code.

Let's add the SET ANSI_NULLS OFF on our previous example and see the output.

SET ANSI_NULLS OFF; -- LET'S TURN OFF THE DEFAULT ANSI BEHAVIOR!

DROP TABLE IF EXISTS temp.dbo.#tempFruits;

CREATE TABLE #tempFruits
(Id INT IDENTITY,
 [Name] NVARCHAR(10) NOT NULL,
 [Description] NVARCHAR(50) NULL);

 INSERT INTO #tempFruits (Name, Description)
 VALUES
 ('Apple', 'The domesticated tree Malus'),
 ('Kiwifruit', NULL),
 ('Pineapple', NULL),
 ('Papaya', 'Also called papaw or pawpaw'),
 ('Cherry', NULL)

 SELECT * FROM #tempFruits WHERE [Description] = NULL -- 3 result
 SELECT * FROM #tempFruits WHERE [Description] IS NULL -- 3 result

 SELECT * FROM #tempFruits WHERE [Description] <> NULL -- 2 result
 SELECT * FROM #tempFruits WHERE [Description] IS NOT NULL -- 2 result


Output


As you can see from the output, when you turn set ANSI_DEFAULT off, the equality operators will eventually be acceptable and work as expected.

So, in incase you experienced this, there's a higher chance that the ANSI_DEFAULT is turned off.
Avoid Changing Default ANSI_NULLS

Turning off the ANSI_NULLS option is not recommended unless you're just trying something or making some quick fixes.

Moreover, it is safer to use the IS NULL and IS NOT NULL operators for the NULL value comparison because it will work in all cases irrespective of the ANSI_NULLS option setting.

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: SQL CAST And CONVERT Function

clock February 9, 2022 07:12 by author Peter

If you're one of those confused about the difference between the CAST and CONVERT functions, you have come to the right place.

That's why in this article, we'll explore the CAST and CONVERT functions of SQL Server and see their difference.

OK, let's get started then.

What is the SQL CAST function?

Basically, this function converts data from one data type to another. For example, it can convert numeric data into character or string data.
Things to Remember about SQL Cast Function

    Transforms the expression data from one data type to another.
    The transformation lasts only for the life of the query.
    It is an ANSI standard (ANSI SQL-92 compliant), portable to other DBMS.
    So if you're comfortable with the CAST function, you'll be able to use it on other SQL-related databases.
    If in case the conversion fails, it will return an error. Otherwise, it returns the converted value.
    Doesn't have a parameter that accepts optional style for formatting. That's why you can use the SQL FORMAT function.

Syntax
CAST([Expression] as DataType (length))

    [Expression] – defines the valid expression argument.
    DataType – the target data type for conversion.
    Length (optional) – the specified length of the target data type.

Examples

Example 1
Let's try to convert a string to DateTime data type.
--Let's declare a type
DECLARE  @YOUR_BIRTHDAY NVARCHAR(10) = '01/29/2000';

--SYNTAX: CAST([Expression] AS DataType)
SELECT @YOUR_BIRTHDAY AS [Data To Convert],
CAST(@YOUR_BIRTHDAY AS DATETIME) AS [BirthDate - Data Converted];


Output

Example 2
Let's add two or more random numbers and convert them into money data type.
--Let's declare two numbers
DECLARE @NUM1 INT = 100, @NUM2 BIGINT = 854775808

--Let's add them together and convert to money and format a bit so it would look like a genuine $. :-)
SELECT FORMAT(CAST ((@NUM1 + @NUM2) AS MONEY), '$ #,##0.00') [Sum];

Example 3
Let's convert two random char data type to int data type and multiply it together.

--Let's declare 2 char with random number assigned to it
DECLARE @char1 CHAR(3) = '100', @char2 CHAR(3) = '569';

--Let's multiply the two char data-type and see the product of those two numbers.
SELECT CAST(@char1 AS INT) * CAST(@char2  AS INT) [Product of Two Numbers]


Output

What is SQL CONVERT function?
This function converts an expression from one data type to another, just like the CAST function. Another good thing about the SQL CONVERT function is that it gives you the option to format your converted data. That's why we can say that it is more powerful compared to the CAST function.
Things to Remember about SQL Convert Function

    A non-ANSI SQL-92 compliant function converts the expression data type to another data type with a formatting option.
    This function is specific to Microsoft's TSQL and will not be portable to other DBMS.

Syntax
CONVERT (DataType, (length), expression, style)

    DataType – target data type to which you want to convert.
    Length – the specified length of the target type.
    Expression – the target data type for conversion.
    Style – optional integer value to specify the style format of the output. Cool right?

Example
Let's create a temp table, insert the data of this year's Chinese New Year, convert it into VARCHAR, and pass some formatting options.
DROP  TABLE IF EXISTS temp.dbo.#CONVERT_FUNCTION_STYLES

CREATE TABLE #CONVERT_FUNCTION_STYLES
(Id int,
 [Name] varchar(10),
 [ConvertedDate] varchar(20))

 DECLARE @CHINISE_NEWYEAR DATETIME = '02/01/2022 12:00:00 AM';

 INSERT INTO #CONVERT_FUNCTION_STYLES
 (Id, Name, [ConvertedDate])
 VALUES
 (1, 'Default', CONVERT(VARCHAR,@CHINISE_NEWYEAR, 100)),
 (2, 'US',      CONVERT(VARCHAR, @CHINISE_NEWYEAR, 101)),
 (3, 'ANSI',    CONVERT(VARCHAR, @CHINISE_NEWYEAR, 102)),
 (4, 'German',  CONVERT(VARCHAR, @CHINISE_NEWYEAR, 104)),
 (4, 'Japan',  CONVERT(VARCHAR, @CHINISE_NEWYEAR, 111));

 SELECT @CHINISE_NEWYEAR [Date and Time To Be Converted],
       Name [Country],
       ConvertedDate [Country Standard Converted Date]

 FROM #CONVERT_FUNCTION_STYLES;


Output

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: Everywhere JSON So Why Not In SQL Server - New Feature In SQL Server

clock February 7, 2022 07:49 by author Peter

If you are a developer then surely you must have used JSON (JavaScript Object Notation) but if not, then don’t worry, you'll use it sooner rather than later. JSON is a kind of ecosystem that is most popular in various areas for exchanging data. If you talk about charting solutions, AJAX, Mobile services, or any 3rd party integration then generally JSON is the first choice of the developers.

Nowadays most of the NoSQL databases like Microsoft Azure Document DB, MongoDB, etc. also use JSON ecosystem and some of them are based on JSON.

As it is such a popular growing system, why not in SQL SERVER?

In SQL SERVER 2016 JSON was introduced. This was step or bridge between NON-relational databases and relational databases by Microsoft SQL SERVER.

SQL Server 2016 provides the following capabilities when you are using JSON

    Parse JSON by relation query
    Insert & update JSON using the query
    Store JSON in the database

If you see it then conceptually it is similar to an XML data type which you might use in SQL SERVER.

The good thing in SQL SERVER 2016 for JSON is there is no Native data type. This will help in migration from any NoSQL to SQL SERVER.

SQL Server provides bidirectional JSON formatting which you can utilize in various ways. Suppose data is coming from the external source in the JSON format then you can parse it and store it in table structure (if required) in another case external source requires data in JSON format while data in SQL SERVER in tabular format so both the purpose can easily solve with SQL SERVER’s JSON feature.

Now, let’s jump directly to the practical to check JSON capabilities in SQL SERVER

1) FOR JSON AUTO
It is similar to FOR XML AUTO. It will return JSON object of selected column where column name is treated as a Key or in other words we can say it will format the query result in JSON.


when you run the above command the result will be like as shown in the below figure.

2) FOR JSON PATH
It’s exactly like JSON auto, the only difference is instead of SQL SERVER we have full control over the format. JSON Auto takes predefined column schema while with JSON path we can create a complex object.

For example, we are using the AdventureWorks Sales order table and joining that with the product table to get a sub-node. As you see below the image we have added a Root node as well. This root Node can be added in JSON auto as well if required.

Now, when you run the above query we can get complex JSON object as follows

3) IsJSON function
By the name, it is clear that this is a validating function.
To cross-check whether the provided string is a valid JSON or not we can run ISJSON.

4) JSON_VALUE
By the name, it is clear that if you want to get the value of the particular key of JSON then you can use this beautiful function which is JSON_VALUE.

5) OPENJSON function
This is a very beautiful function that you can use to parse external schema. Suppose, you got a JSON string from a mobile service that you will directly pass to SQL Server, and the SQL SERVER stored procedure will do the rest of the operation to parse it. The parsing and other operation can be easily handled by OPENJSON. The only tweak here is that it required database compatibility level 130 which you need to do (if not compatible with level 130)


There are many other interesting things which we will cover later.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



SQL Server Hosting - HostForLIFE :: Email Notification On SQL Job Failure

clock February 3, 2022 07:25 by author Peter

In this article, we will discuss how to send email notifications when our SQL job fails. The purpose to configure is to intimate the user to take care of failed jobs. We will cover how to configure Database Mail, Email profile, SMTP Configuration, Operator to send email, notification, and SQL Server Agent configuration.

We know to perform a series of actions automatically on SQL server side, we need to configure jobs. A task that is configured will be run one or more times and monitored for success or failure. Some examples of SQL jobs are daily, weekly, monthly and quarterly reports, sending auto emails, newsletters, writing log files, and audit logs to be sent automatically on local or remote locations.

Why Configure Email Configuration?

When our job is running and we can face any issue while executing the script. Such issues occurred when working with files, simultaneously data insertion, working with SSDT (SQL Server Data Tools), and many more scenarios. SQL job get stuck and take more time as expected and finally fails. On job failure, we need to know on an immediate basis to get rid of the problem.

Steps to Configure Email Notification on Failure
These are steps to be performed to configure email notification on SQL job failure:

Step 1
Under Management, Configure Database Main. Right click on Database Mail and select the first option (Configure Database Mail)

 



Step 2
We are creating a new profile, so select the first option and click on Next.

Step 3
Write the profile name and description then click on Add button to add SMTP settings.

Step 4
I am using Gmail SMTP configuration; you can use according to your settings. From email address is used to send email notifications.



Step 5
When profile is ready then click Next to proceed.

Step 6
Configure your system level parameters like retry mechanism, attached files size, and allowed/prohibited extensions. Click on Next. On next screen shows all the details of your account simply select Finish. Your all configuration is successfully built.

Step 7

Create an Operator
Now we have to make an operator to whom you want to send email when the SQL job is failed
Expand SQL Server agent
Right-click on Operators and select new operator


Step 8
In the following screen enter your Operator name and E-mail name to whom you want to send emails. If you want to send email to more than one person just separate the email address with ';'

After that click OK and operator is ready to send emails.


Step 9
Create a New SQL Job

Step 10
Select Notifications and check on email and select operator which we define previously.
It helps to send email when the jobs fail. After that click on OK.


HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: A Simple Way To Check Vulnerability Status Of Your SQL Server Database

clock January 24, 2022 09:27 by author Peter

As a product owner, you are always worried about the different security aspects of your application, and SQL Server Database is one of the main important parts for which you might worry.

And you always think there should be some kind of checklist which you or your team have to check whether your database is secure or not and find all the vulnerabilities.

And obviously, you might have purchased different tools for this assessment as well that will provide you security loopholes but when we talk about Databases the option is limited and some options are very costly.

With SQL SERVER 2017 latest SQL Management Studio one of the problems will be resolved cross-check your database vulnerability.

You heard it right. Although, this feature is already available in SQL Azure now you can do this assessment of your database using SQL Server 2017’s management studio.

This vulnerability assessment report can be generated on the database with a few simple clicks and you will get different High, Medium, Low risks of your database.

The vulnerability assessment report not only provides risks details but also helps you to identify which category of it and this will not stop here you will get a recommendation as well to fix those problems. Sometimes, you will get direct scripts that you can run to fix those issues, and sometimes you will get the links on how to implement those.

Let’s understand this by step-by-step action.

Before starting make sure you have SQL Server 2017 Management Studio’s latest version.

Step 1
Once you opened the SQL Server management studio right click on the database which you want to cross-check. in this example, I am using the AdventureWorks database. As shown in the below figure.


Here you have 2 options either Scan for Vulnerabilities or Open Existing Scan

Step 2
Now, as we are doing it the first time click on Scan for Vulnerabilities option. and you will get the following screen where you can provide the location of the scan file.


Step 3
Just click on the OK button to proceed further and wow you will get all the loopholes of your database.
You can easily check what are different points on which your Database is failed with risk Assessment.

As shown in the above figure, we have 6 checkpoints on which our database failed in which 1 is on high risk, 3 medium risk, and 2 Low risks.

And if you see carefully there are different categories as well like data protection, Authentication, and Authorization, Surface Area Reduction, etc.

Here as the name suggests Data Protection is mostly related to encryption of your sensitive data like SSN, DOB, etc, or TDE.

Authentication and Authorization are more related to login access to the database.

Surface Area reduction is more related to what extra option you have opened.

Step 4

Now, move a step further and click on any row in the grid. You will find the details of the row just below the grid. As you can see below the image when we click on data protection it suggests the column names which come under extra care and to on which we might think to apply encryption.

 

Step 5
The story does not end here, for some of the problems this assessment report provides a script as well, and if the script is not possible then provide a reference link to resolve that issue.

As you can see in the below screen we are getting recommendation scripts to apply.


Isn’t it cool and simple to assess your database’s vulnerability in a few clicks and secure your database?

Share your thoughts.

HostForLIFEASP.NET SQL Server 2022 Hosting



SQL Server Hosting - HostForLIFE :: Retrieving Table And Function In A Procedure

clock January 12, 2022 08:08 by author Peter

This is a query which will help to retrieve all the tables and functions used in a store procedure, even if the query is a dynamic one.
SELECT objects.name As suspected_dependencies
FROM   sys.procedures
 INNER
  JOIN sys.all_sql_modules
    ON all_sql_modules.object_id = procedures.object_id
 LEFT
  JOIN sys.objects
    ON objects.name <> procedures.name
   AND all_sql_modules.definition LIKE '%' + objects.name + '%'
WHERE  procedures.name = <Procedure Name>

Output

HostForLIFEASP.NET SQL Server 2019 Hosting



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in