European Windows 2012 Hosting BLOG

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

SQL Server 2016 Hosting - HostForLIFE.eu :: TRIM Function In SQL Server 2017

clock February 20, 2019 10:22 by author Peter

With the release of SQL Server 2017, a new TRIM() is also introduced which helps to remove the white space/characters from both sides of a string. Before 2017, this functionality was achieved by using the following SQL functions.
    REPLACE - used o replace a character from a string
    LTRIM - trim the white spaces from the left side of a string
    RTRIM - trim the white spaces from the right side of a string

I can explain the functionality with two scenarios.

Let's assume, we have a string named ' ABC ' and we are going to eliminate the white spaces from both sides of the string.
 
In SQL, we usually use the LTRIM and RTRIM function like in the code below.
    SELECT LTRIM( RTRIM(' ABC ')) 

Now, this can be done by using a single TRIM function.
    SELECT TRIM(' ABC ') 

Test results from SSMS can be seen below.

Assume we have a string named 'X ABC Y' and we need to extract 'ABC' from that. As usual, we will go with the REPLACE function as follows.
    SELECT REPLACE(REPLACE('X ABC Y','X ',''),' Y','') 

Here you go with the TRIM function.
    SELECT TRIM('XY ' FROM 'X ABC Y') 

Test results from SSMS are shown below.

Note - It is necessary that you have to mention the trailing charter in the TRIM function, otherwise, this will not work as expected.
 
For example, if you try to remove the 'white space' only from the string 'X  ABC  Y', then TRIM will not help you. Similarly,  if you don't mention the letter 'Y', TRIM will not remove the white space after the string, even though you already mentioned the 'X' and the 'white space' characters inside the TRIM function. See these scenarios in the below screenshot.
 
Test results from SSMS,

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 :: Maximum Limit Value For Integer Data Type in SQL Server 2012

clock November 27, 2018 10:12 by author Peter

In this article, I described how to calculate the maximum range of various integer data types in SQL Server. TINYINT, SMALLINT, INT and BIGINT are all number data types. The difference between these data types are in the minimum and maximum values. So let's have a look at a practical example of how to calculate the maximum range of the integer data type in SQL Server. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

Calculating the maximum range of various integer data types.

Bigint Data Type
The Bigint data type represents an integer value. It can be stored in 8 bytes.

Formula   2^(n-1) is the formula of the maximum value of a Bigint data type.
In the preceding formula N is the size of the data type. The ^ operator calculates the power of the value.
Now determine the value of N in Bit:
Select (max_length * 8) as 'Bit(s)' from sys.types Where name = 'BIGInt' 

 

Determine the maximum range of Bigint
The formula is:
2^(n-1) here N=64

Select Power(cast(2 as varchar),(64) -1) as 'Bigint max range'  from sys.types Where name = 'BIGInt'

The range of a Bigint data type is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

INT Data Type
Int represents an integer value that can be stored in 4 bytes. INT is the short form of integer.

Formula
2^(n-1) is the formula to find the maximum of an INT data type.
In the preceding formula N is the size of data type. The ^ operator calculates the power of the value.

Now determine the value of N in Bit:
Select (max_length * 8) as 'Bit(s)' from sys.types Where name = 'Int'

Determine the maximum range of int
The formula is:
2^(n-1) here N=32
Select Power(cast(2 as varchar),(32) -1) as 'int max range'  from sys.types Where name = 'Int'

The range of an int data type is -2,147,483,648 to 2,147,483,647.

Smallint Data Type
Smallint represents an integer value that can be stored in 2 bytes.

Formula 
2^(n-1) is the formula to find the maximum of a Smallint data type.
In the preceding formula N is the size of the data type. The ^ operator calculates the power of the value.

Now determine the value of N in Bit:Select (max_length * 8) as 'Bit(s)' from sys.types Where name = 'Smallint'

Determine the maximum range of Smallint
The formula is:
2^(n-1) here N=64
Select Power(cast(2 as varchar),(16) -1) as 'Smallint max range'  from sys.types Where name = 'SMALLInt'

The range of a Smallint data type is -32768 to 32767.
Tinyint Data Type
Tinyint represents an integer value that can be stored in 1 byte.
The range of a Tinyint data type is 0 to 255.

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 :: All About Primary Key And Its Basics

clock November 7, 2018 08:44 by author Peter

In this series of articles, we will go deep into SQL Server from scratch and will gain knowledge of queries, optimization, and database administration. This is the first article of the series where we will learn about general SQL queries and their functioning. Images have been used wherever necessary so as to make you understand every command properly.

All Queries which I am posting today you can use  directly on your query plan like copy, paste and execute this query.
Each query has a valid column name and similarly I have shown in the form of image for proper understanding and proper usage

Find all Primary key in Give Database in following format,

SELECT i.name AS IndexName, 
    OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
    COL_NAME(ic.OBJECT_ID, ic.column_id) AS ColumnName 
FROM sys.indexes AS i 
INNER JOIN sys.index_columns AS ic 
ON i.OBJECT_ID = ic.OBJECT_ID 
AND i.index_id = ic.index_id 
WHERE i.is_primary_key = 1  


Finding Constrains and Type of Constrain i.e. Primary and foreign key relation in the given database

SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint, 
    SCHEMA_NAME(schema_id) AS SchemaName, 
    OBJECT_NAME(parent_object_id) AS TableName, 
    type_desc AS ConstraintType 
FROM sys.objects 
WHERE type_desc IN('FOREIGN_KEY_CONSTRAINT', 'PRIMARY_KEY_CONSTRAINT')  


Detailed level relationship and description of primary key and foreign key

SELECT f.name AS ForeignKey, 
    SCHEMA_NAME(f.SCHEMA_ID) SchemaName, 
    OBJECT_NAME(f.parent_object_id) AS TableName, 
    COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName, 
    SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName, 
    OBJECT_NAME(f.referenced_object_id) AS ReferenceTableName, 
    COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName 
FROM sys.foreign_keys AS f 
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id 
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id 


Use the above snippets as per your requirement.

In most of the cases it's is going to be used in the Database Analysis where Database size and table are large and high in number.

Thus, we learned about the basic queries of SQL. If you have some doubt, or want to add some more information in this article, please feel free to write me in the comments section.

 

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 Use TRY CATCH In SQL Procedure?

clock October 10, 2018 11:18 by author Peter

In this post, we will learn how to use TRY CATCH in SQL procedure and store an error with error text. Here is a simple example for generating the error and storing it in a SQL table. Let's start coding. For saving the error in the table first we need to create the table in SQL Database. See below.
    CREATE TABLE [dbo].[Error_StoreProcedure]( 
        [ID] [bigint] IDENTITY(1,1) NOT NULL, 
        [ErrorNumber] [varchar](50) NULL, 
        [ErrorSeverity] [varchar](50) NULL, 
        [ErrorState] [varchar](50) NULL, 
        [ErrorProcedure] [varchar](500) NULL, 
        [ErrorLine] [varchar](50) NULL, 
        [ErrorMessage] [varchar](max) NULL, 
        [EntryDate] [datetime] NULL, 
     CONSTRAINT [PK_Error_StoreProcedure] PRIMARY KEY CLUSTERED  
    ( 
        [ID] ASC 
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 
    GO

After creating the above table we need to create one procedure for saving the error in the table;  see below.
 CREATE PROCEDURE usp_GetErrorInfo   
    AS   
    BEGIN 
        INSERT INTO Error_StoreProcedure SELECT   
        ERROR_NUMBER() AS ErrorNumber   
        ,ERROR_SEVERITY() AS ErrorSeverity   
        ,ERROR_STATE() AS ErrorState   
        ,ERROR_PROCEDURE() AS ErrorProcedure   
        ,ERROR_LINE() AS ErrorLine   
        ,ERROR_MESSAGE() AS ErrorMessage 
        ,dbo.GetDateTimeZone()   
    END


After creating the above procedure now we have to use the above procedure inside the other procedure.
    CREATE PROCEDURE TESTING_ERROR_PROCEDURE 
      
    AS 
    BEGIN 
     SET NOCOUNT ON; 
     
        BEGIN TRY   
             
            -- Generate divide-by-zero error.   
            SELECT 1/0;   
         
        END TRY   
        BEGIN CATCH   
             
            -- Execute error retrieval routine.   
            EXECUTE usp_GetErrorInfo;   
         
        END CATCH;    
     
    END 
    GO


The above procedure generates the error and goes to the CATCH part and saves all information of the error into our error table.
Run this query SELECT * FROM Error_StoreProcedure

See the output of the above table. Output displays procedure name and line number of the error.

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 :: 10 SQL Server Shortcuts You Must Know

clock September 6, 2018 08:30 by author Peter
SQL Server is a relational database management system (RDBMS) developed by Microsoft. As a Database Server, it is a software product with the primary function of storing and retrieving data as requested by other software applications, which may run either on the same computer or on another computer across a network. Many developers are familiar with using some of the below listed shortcuts for SQL Server Management Studio. Using keyboard is always a preferred way of working as it boosts the working speed tremendously. Thus, I thought of sharing my experience listing these shortcuts that I usually find helpful while working with SQL Server Management Studio.

New Window
CTRL + N: Open up a new query Window in SQL Server Management Studio (SSMS).

Comment Code
CTRL + K, CTRL + C: Comment the selected text.
CTRL + K, CTRL + U: Uncomment the selected text.

Go to Line
CTRL + G: Go to specified line number in the current query window.

Result Pane
CTRL + R: Shows/Hides the Result Pane. Toggle the query results.
CTRL + T: Display results to Text
CTRL + D: Display results to Grid
CTRL + SHIFT + F: Display results to File

Change Case

CTRL + SHIFT + U: TChange the selected text to UPPER CASE.
CTRL + SHIFT + L: Change the selected text to lower case.
 
IntelliSense
CTRL + SPACE, TAB: Using Ctrl + Space, suggestions would be given, and using Tab, you can complete that suggestion.
Query Execution
F5 or ALT + X or CTRL + E: Execute all the queries written on query window.
CTRL + F5: Parse the query to check if there are any syntax errors.

Profiler
CTRL + ALT + P: Open up SQL Server Profiler. Profiler is generally used for tracing and analysing.

System SP
ALT + F1 (Select any stored procedure on query editor and press ALT + F1) : It runs the sp_help system stored procedure.
CTRL + 1: In the same way, it runs the sp_who system stored procedure. It will provide you the details like who created the SP, spid, host name, on which DB the SP was created and so on.
Screen
SHIFT + ALT + ENTER: Toggle full screen mode.
I hope you found the post "Ten SQL Server Shortcuts You Must Know" useful and worth reading.

What do you think?
If you have any questions or suggestions, please feel free to email us or put your thoughts in the  comments below. We would love to hear from you. If you found this post useful, please share with your friends and help them to learn.

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 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, '[email protected]')

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 :: 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 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.



SQL Server 2016 Hosting - HostForLIFE.eu :: Auto Query Generator In MSSQL Server

clock July 26, 2018 08:01 by author Peter

If you’re a developer, irrespective of the platform, you  have to work with databases. Creating SQL statements for tables is quite often a monotonous job and it gets hectic especially when dealing with gigantic tables that have hundreds of columns. Writing SQL statements manually every time becomes a tiresome process. Before explaining the script, I want to share the reason to write this script and how it is helping my peers. We have code standard on the database side. Below points are standards.

  • Need to maintain a separate stored procedure to every table
  • Don’t use * in the query instead specify the column
  • Use the correct data type and size of a column
  • Every parameter should be nullable in a stored procedure.

I am developing an application which is related to machines using .NET and SQL Server. The database design consists of some master tables and transactional tables. All the transactional table has more than 30 columns.

To meet my code standards, I need to mention all columns with correct data type and size in stored procedure parameters like below,
CREATEproc [dbo].[USP_PCNitemCreation] ( @Id int, @machineName varchar(50)=NULL, @furnacename varchar(50)=NULL, @minValue int=NULL, @maxValue int=NULL, @createdDate datetime=nullvarchar(100)=NULL ) 

All the queries should specify the column instead of using the start(*).
select machineName,furnacename from trn_furnace where Id=@Id 

It consumes more time and is a boring task. So, I plan to write the script to is cut down on the time it takes and boring repeated work. We cannot automate the logic, but we can automate the repeated task.

Then I write the below script which really cuts down on all of our above pain points.

Auto Query Generator Stored Procedure for MSSQL Server,
CREATEproc [dbo].[USP_QuerycreationSupport] ( @table_Name varchar(100)=NULL ) AS  
BEGINDECLARE @InserCols   NVARCHAR(max)DECLARE @Inserparam  NVARCHAR(max)DECLARE @Insertquery NVARCHAR(max)DECLARE @Selectquery NVARCHAR(max)DECLARE @Update      NVARCHAR(max)DECLARE @DeleteQuery NVARCHAR(max) 
  -- sp paramSELECT '@'+c.NAME+Space(1)+Casecast(t.Nameasnvarchar(40))WHEN'nvarchar'THEN  
  t.NAME    +'('+cast(c.max_length asnvarchar(30))+')'  
WHEN'varchar'THEN  
  t.NAME+'('+cast(c.max_length asnvarchar(30))+')'  
WHEN'char'THEN  
  t.NAME+'('+cast(c.max_length asnvarchar(30))+')'  
WHEN'decimal'THEN  
  t.NAME        +'(18,2)'  
  ELSE t.nameend+'=null,'AS colss FROM sys.columns c innerjoin sys.types t ON c.user_type_id = t.user_type_id leftouterjoin sys.index_columns ic ON ic.object_id= c.object_idand ic.column_id = c.column_id leftouterjoin sys.indexes i ON ic.object_id= i.object_idand ic.index_id = i.index_id WHERE c.object_id=object_id(@table_Name)SELECT'Insert query'SET @InserCols=(selectdistinct  
  (  
         select sc.NAME+','  
         FROM   sys.tables st innerjoinsys.columns sc  
         ON st.object_id= sc.object_id  
         WHERE  st.NAME= @table_Name forxmlpath(''),  
                type).value('.','NVARCHAR(MAX)'))  
  -- Return the result of the functionSELECT @InserCols=LEFT(@InserCols,Len(@InserCols)-1)  
  --select @InserColsSET @Inserparam=(selectdistinct  
  (  
         select'@'+sc.NAME+','  
         FROM   sys.tables st innerjoinsys.columns sc  
         ON st.object_id= sc.object_id  
         WHERE  st.NAME= @table_Name forxmlpath(''),  
                type).value('.','NVARCHAR(MAX)'))  
  -- Return the result of the functionSELECT @Inserparam=LEFT(@Inserparam,Len(@Inserparam)-1)  
  --select @InserparamSET @Insertquery='insert into '+@table_Name+'('+@InserCols+')'+'values'+'('+@Inserparam+')'SELECT @InsertquerySELECT'Update Query'SET @Update=(selectdistinct  
  (  
         select sc.NAME+'=@'+sc.NAME+','  
         FROM   sys.tables st innerjoinsys.columns sc  
         ON st.object_id= sc.object_id  
         WHERE  st.NAME= @table_Name forxmlpath(''),  
                type).value('.','NVARCHAR(MAX)'))  
  -- Return the result of the functionSELECT @Update=LEFT(@Update,Len(@Update)-1)  
  --select @UpdateSET @Update='UPdate '+@table_Name+' set '+@UpdateSELECT @Update  
  -- For select QuerySELECT'Select Query'SET @Selectquery='select '+@InserCols +' from '+ @table_NameSELECT @Selectquery 
  -- For Delete QuerySELECT'Delete Query'SET @DeleteQuery='delete from '+ @table_NameSELECT @DeleteQuery 
end 


How to use this script,
Step 1 - Create the stored procedure using the above code or attached code.
Step 2 - Execute the stored procedure and pass your table name as a parameter.
Exec USP_QuerycreationSupport@table_Name='mstCustomer' 

Should not pass the database object in the table name
Exec USP_QuerycreationSupport@table_Name='[dbo].[mstCustomer]' 

Once you execute the Stored Procedure as mentioned above, you get all the SQL statements as shown here. You could easily use the generated SQL statements elsewhere. You get all basic SQL statements like Select, Insert, Update & Delete.


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 2016 Hosting - HostForLIFE.eu :: FOR JSON Clause With AUTO Mode In SQL Server 2016

clock July 24, 2018 07:26 by author Peter

In the release of SQL Server 2016 CTP 2 one of the features that was introduced is JSON clause. So, the first question that comes into everyone’s mind is What is JSON? JSON stands for JavaScript Object Notation. JSON is a lightweight format which is used for storing and interchanging the data. JSON uses standard JavaScript functions to convert the JSON data into native JavaScript objects. The main purpose of using FOR JSON is used to create new JSON objects. We can format the query results using FOR JSON clause in these ways,
With AUTO mode
With PATH mode
With ROOT option
Output with INCLUDE_NULL_VALUES option


In this blog, we will discuss the query formatting using FOR JSON clause with AUTO mode option.

Syntax for FOR JSON clause with AUTO option is like this:
FOR JSON AUTO

When AUTO option is used, the format of JSON is determined automatically on the basis of the number of columns present in the SELECT statement list. A FROM clause is necessary inquery with FOR JSON AUTO option.

When you join tables, columns present in the first table are used as properties of the root object in JSON array while columns present in the second table will be automatically formatted as a nested object within the root object.

Let’s execute the below query and see the JSON output.
SELECT sp.BusinessEntityID, 
   sp.TerritoryID, 
   st.CountryRegionCode, 
   st.[Group] TerrritoryGroup 
   FROM sales.salesperson sp 
   JOIN Sales.SalesTerritory st ON sp.TerritoryID = st.TerritoryID 
   WHERE sp.TerritoryID = 10 
FOR JSON AUTO 

After executing the above query, we get the output in this format.
[{ 
    "BusinessEntityID": 289, 
    "TerritoryID": 10, 
    "st": [{ 
        "CountryRegionCode": "GB", 
        "TerrritoryGroup": "Europe" 
    }] 
}]

Brackets [ ] represents JSON array in output.

Here, in the output, we can see that table Sales.SalesTerritory is automatically formatted as a nested object under parent object.

So we have generated a formatted query output using JSON clause. I will continue with other ways of formatted output using JSON clause in my next blogs.

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