European Windows 2019 Hosting BLOG

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

SQL Server 2021 Hosting - HostForLIFE :: Bulk Data Insertion In SQL Table Using Union ALL

clock July 19, 2022 09:31 by author Peter

We are going to discuss bulk data insertion from multiple tables

    There are many scenarios in which we want to insert a large amount of data from one table to another which has the same schema and all things
    We discussed two ways to insert bulk data manually inside the SQL Table using UNION ALL
    Also, after selecting the data from one table using select query and then inserting that into another by using insert and select query with the help of union all

Let’s start

Step 1
Create a Product Table inside the database
CREATE TABLE DummyProduct (
    ProductID int,
    ProductName varchar(255),
    ProductDescription varchar(255),
    ProductPrice varchar(255),
    ProductStock varchar(255)
);

Step 2
First, we look manual process
select 1, 'Mobile', 'IPhone 12', 80000, 200
UNION ALL
select 2, 'Laptop', 'HP Pavilion 15', 100000, 100
UNION ALL
select 3, 'TV', 'Samsung Smart TV', 35000, 300


Here, you can see we use multiple select queries with union all, you will see the following output after executing all the above query

Step 3
Now, we are going to insert all data in the Product table in only one transaction
INSERT into Product
select 1, 'Mobile', 'IPhone 12', 80000, 200
UNION ALL
select 2, 'Laptop', 'HP Pavilion 15', 100000, 100
UNION ALL
select 3, 'TV', 'Samsung Smart TV', 35000, 300


Here see first we write insert query and below that put all select query using union all and when we execute all this bunch of SQL Query at a time then all the data which are present in the select query is inserted into the product table as shown below

(Note – The number of columns that are present in the select query will be the same as present in the targeted table)

Step 4
Now we are going to insert the Product table records into the new DummyProduct Table with adding new one record as shown below
--Create DummyProduct Table
CREATE TABLE DummyProduct (
    ProductID int,
    ProductName varchar(255),
    ProductDescription varchar(255),
    ProductPrice varchar(255),
    ProductStock varchar(255)
);

--Insert data in bulk
INSERT into DummyProduct
select * from Product
UNION ALL
select 4, 'Keyboard', 'HP Gaming Keyboard', 2000, 400

//select all the record
select * from DummyProduct


Here, you can see we write insert query of DummyProduct and below that put two select query. One takes three records from Product table and the second one takes one record from the static select query, after executing all the above SQL Queries at a time you will see below output as I showed below.

This is all about the bulk insertion of the table using union all.

HostForLIFEASP.NET SQL Server 2021 Hosting

 



SQL Server 2021 Hosting - HostForLIFE :: How To Rename Database Objects In SQL Server

clock July 14, 2022 09:19 by author Peter

This article demonstrates how we can easily rename various database objects like Tables, Columns, Constraints, Indexes, SP in SQL Server. You may have faced a scenario where sometimes we need to rename database objects to specify correct business significance and meaning to the system on production code. The database objects which were originally designed may not match the current business objects. To solve this problem, you may need to rename existing database objects like table name, column name, store procedure name, etc. The best and easiest way is to use SP_RENAME, a build-in stored procedure to rename these objects.

This approach is recommended because we can run pre-deployment scripts in the environment before deploying these changes.

SP_RENAME takes below arguments.

Parameter Description
@objname Object Name. When renaming a column you need to specify table name.column name optionally you can also prefix schema name
@newname New name for the specified object
@objtype Type of the object. You can rename below objects using sp_rename:
COLUMN
DATABASE
INDEX
OBJECT
STATISTICS
USERDATATYPE
Default value for this parameter is TABLE

To demonstrates this, I am creating a table with Primary key, check constraint, non-clustered index and putting some data into this table. We will compare before and after snapshots.

CREATE TABLE OrderInfo
(
  Id INT IDENTITY(1, 1) NOT NULL,
  OrderMode VARCHAR(20) CONSTRAINT [CK_OrderInfo_OrderMode] CHECK (OrderMode IN ('ONLINE','OFFLINE')) NOT NULL,
  OrderName VARCHAR(100) NOT NULL,
  OrderDate DATETIME CONSTRAINT [DF_OrderInfo_OrderDate] DEFAULT (GETDATE()) NOT NULL,
  CONSTRAINT PK_OrderInfo_Id PRIMARY KEY NONCLUSTERED (Id ASC)
)

CREATE NONCLUSTERED INDEX IX_OrderInfo_OrderMode ON dbo.OrderInfo (OrderMode)

INSERT INTO  OrderInfo
VALUES
    ( 'ONLINE', 'Notebook', GETDATE()),
    ( 'ONLINE', 'PC', GETDATE()),
    ( 'OFFLINE', 'Printer', GETDATE())
GO

Before snapshot of table, constraints, and index.

 

Rename a Table
--Rename table OrderInfo to OrderSummary
EXEC SP_RENAME 'dbo.OrderInfo', 'OrderSummary'


Rename a Column
--Rename column Id to OrderSummaryId
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME= 'OrderSummary' AND COLUMN_NAME='Id')
BEGIN
EXEC SP_RENAME 'dbo.OrderSummary.Id', 'OrderSummaryId'
END


Rename an Index
--REANME INDEX
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name='IX_OrderInfo_OrderMode' AND OBJECT_ID = OBJECT_ID('dbo.OrderSummary'))
BEGIN
EXEC SP_RENAME 'dbo.OrderSummary.IX_OrderInfo_OrderMode','IX_OrderSummary_OrderMode','INDEX';
END


Rename a Primary Key Constraint
--REANME PRIMARY KEY CONSTRAINT
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME ='PK_OrderInfo_Id')
BEGIN
EXEC SP_RENAME 'dbo.PK_OrderInfo_Id','PK_OrderSummary_OrderSummaryId','OBJECT';
END

Rename a Check Constraint
--REANME CHECK CONSTRAINT
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME ='CK_OrderInfo_OrderMode')
BEGIN
EXEC SP_RENAME 'dbo.CK_OrderInfo_OrderMode','CK_OrderSummary_OrderMode','OBJECT';
END


Rename a Stored Procedure
--RENAME SP
EXEC SP_RENAME 'dbo.spGetOrderInfoByOrderMode' , 'spGetOrderSummaryByOrderMode';


Let’s verify the changes have been made by issuing a SELECT against the table using new table name.


One thing to keep in mind is that when we rename these objects, we need to make changes in dependencies of these objects. For example – if you are renaming a table and that table is being used in multiple SPs then we also to modify those SPs as well. But that is a manual activity to find and fix. This warning represents the same thing.


Hope you find this information useful. Happy Learning!



SQL Server 2021 Hosting - HostForLIFE :: Remove Duplicate Reversed Pairs

clock July 5, 2022 08:49 by author Peter

In this article, we will learn how to remove all reversed number pairs from given table, keep only one (random) in output table if something exists. This SQL problem is a often asked in interview questions, so this have been asked by multiple companies for the data analyst, data science and data engineering interviews. And in this input table for this simplicity we can consider there will be one entry for such kind thing like (1,2) and (2,1) can only be exist once there won't be any such entries like one entry for (1,2) and (2,1) repeated twice or thrice. This is our SQL problem in this article we are going to solve the statement.

Using join operation and where clause
At first we need create a database (here in my case database name is example) then create a table (here in my case i have taken table name is details) now insert some dummy data by using below SQL Query

create database example;
use example

create table details(A int, B int)
insert into details values(1,2);
insert into details values(3,2);
insert into details values(2,4);
insert into details values(2,1);
insert into details values(5,6);
insert into details values(4,2);


now check the table data using below query
select*from details

Output

So first try to solve it using the join operation. so here first let me explain how this is going to work so we can do this self join operation with a condition to change those pairs together (1,2) , (2,1) , (2,4) and (4,2).  We can apply where condition where we can eliminate anyone of it either (1, 2) or (2, 1) for the self a join operation. The on condition which is writing. That is little bit tricky, not very complex to understand and how we can actually change these two pairs together (1, 2) to (2,1) So let's say this is my table T1 and again we are using these self join here. So that table we can name it as a T2. So what we actually need to check in the on condition for the table T1 the column of value B should be equals to the column of value A in T2 table and the second condition part will be the column value of A from table T1 should be equal to the column value of B from the T2 table.

So this would be our join condition. So first let me try to write that join condition for you. Then it will be more clear to you. So here what we're trying to do, we will be doing a left join operation while left join again with this table number pairs and we will name it as a T2 and what would be my join condition. The join condition will be value of B column from T1 table should be equals to value of A from the T2 table. And the second part of the condition will be T1 of A Should be equals to T2 of B or directly you can use the below code:

SELECT  *  FROM details t1
LEFT JOIN details t2
  ON t1.B = t2.A
  AND t1.A = t2.B;


Output

See the below snapshot. Blue highlighted data is coming from the table T1 and Red highlighted data is actually coming from the table T2.

So you can see simply how this pair (1,2) got chained with (2,1)  based on just above mentioned code condition since (3,2) there was nothing as such available. That's why I use left join. Because we will be using these null related values in order to filter these pairs as well because we need it in our output. so this one is clear that how it got joined and when we will come to this pair (2,4) this one reversed pair was (4,2) and now (2,1) Obviously this condition will get satisfied because we're doing a self join, so this pair will find this one as a reversed pair and that's why it is being populated here for (5,6) there was number such reverse pair exist, so that's why these values are null and (4,2) we found (2,4) and now we need to print our output. An in our output, if you remember the values were like this among these two pairs (1,2) and (2,1) . We were picking this single value only and how we were actually picking single value, the value from the column A from table T1 should be less than the value of column A from the table T2. This kind of comparison we can put and this way we will be only able to pick this pair and we will be discarding the repeated values and same thing applies for (2,4) and (4,2)  and we need these records as well. So simply we can put a check for this column right where the T2.A is null. In that case we're simply picking single value. No need to check for any quality related thing. So this is our join part. We need to select the columns which we want in our final output so that we are going to select from T1 table itself T1.B once we are getting the join output then we are applying where clause, first where clause will be that if this value of A  column from T2 is null then straight forward we are going to pick these records. There is no further checking required or let's say this is populated. In that case we need to apply the logic for the value of column A from T1 table should be less than value of. A column from the T2 table. That's how we are going to pick any of one among these two like (1,2) to (2,1). Now let me print this one and here, we can see the output which we were looking for or directly you can use the below code:

SELECT
  t1.A,
  t1.B
FROM details t1
LEFT JOIN details t2
  ON t1.B = t2.A
  AND t1.A = t2.B
WHERE t2.A IS NULL
OR t1.A < t2.A;


Output

HostForLIFEASP.NET SQL Server 2021 Hosting

 



SQL Server 2021 Hosting - HostForLIFE :: SQL's STRING_AGG Function

clock June 23, 2022 08:19 by author Peter

Before SQL Server 2017 (SQL Server 2014 below), concatenating rows of strings into one column could be done using the STUFF function that combines with FOR XML PATH. However, in my opinion, it's quite messy. In this article, we'll explore SQL's STRING_AAG function and see how we can concatenate rows of strings into one column string using a separator.

The examples provided will work with SQL Server 2017 and later.

Ok, let's get started.

What's SQL's STRING_AAG Function?

    It is an aggregate function that concatenates strings into a single line separated by a separator.
    The separator is not appended to the end of the result string.
    This function was introduced into SQL Server 2017 and later.

Syntax
STRING_AGG(string expression, separator) [order clause]
    The string expression could be any type.
        It can be converted into VARCHAR or NVARCHAR during concatenation.
        Non-string types are converted to NVARCHAR types.
    The separator is used as a separator for the concatenated strings.
        It can be literal or variable. Just remember it doesn't add itself at the end of the result string.
    The order clause is the sort order of the result string using the WITHIN GROUP clause.

Syntax of WITHIN GROUP
WITHIN GROUP (ORDER BY expression [ASC | DESC])
    The expression can be used for sorting results; only one expression is allowed per query.
        The default order is ascending.

Examples
Before we show examples, the AdventureWorks database will be used for the first of our samples.
Using STRING_AGG First Example

To have an overview, the [Sales].[SalesOrderHeader] under the AdventureWorks database does have a [SalesOrderNumber] column.

And we wanted to show the list of different sales-order-number per customer by using the STRING_AGG function.

Ok, let's see the examples below.

SELECT CustomerID as [Customer ID],
       COUNT(CustomerID) as [Number Of Sales Order] ,
       STRING_AGG([SalesOrderNumber], ',') as [Sales Order List]
FROM [AdventureWorks2019].[Sales].[SalesOrderHeader]
GROUP BY CustomerID


As you can see, with the query that we have we did get the [CustomerID] column as our reference for a particular customer.

Then by knowing the number of its records, we can show the different sales-order numbers per record.

But, of course, using the STRING_AGG.

That's why we can come up with the query above.

Let's see the output below.

Output

Now, for us to appreciate the WITHIN GROUP syntax when using STRING_AGG.

Let's look at the example below.

SELECT CustomerID as [Customer ID],
       COUNT(CustomerID) as [Number Of Sales Order],
       STRING_AGG([SalesOrderNumber], ',')
       WITHIN GROUP (ORDER BY [SalesOrderNumber] DESC)
       as [Sales Order List]
FROM [AdventureWorks2019].[Sales].[SalesOrderHeader]
GROUP BY  CustomerID


Output

Now, let's try to see the difference between the two outputs.

Output Difference

Using STRING_AGG Second Example
In this section, I will try to give another example. The idea here is to get all the phone numbers of a particular customer; it seems easy, right?
Yap, let's show the code now, and let's create the table structure.

Note: We'll use a local temporary table to avoid tabl structure complexities.

Build the structure first.
-- 1. Let's create the tables needed.
IF OBJECT_ID(N'tempdb..#Customers') IS NOT NULL
BEGIN
    DROP TABLE #Customers
END

CREATE TABLE #Customers(
    Id int,
    FirstName nvarchar(50),
    LastName nvarchar(50)
)

IF OBJECT_ID(N'tempdb..#CustomersPhone') IS NOT NULL
BEGIN
    DROP TABLE #CustomersPhone
END

CREATE TABLE #CustomersPhone(
    PhoneId int,
    UserId int,
    PhoneNumber nvarchar(50)
)

Second, let's put some data on it.
-- 2. Let's put some data on it.

INSERT INTO #Customers VALUES
(1, 'Peter', 'Scott'),
(2, 'Mark', 'Tom')

INSERT INTO #CustomersPhone
VALUES
(1, 1, '+63 895 789 5751'),
(2, 1, '+63 795 689 5752'),
(3, 1, '+63 695 589 5753'),
(1, 2, '+63 915 739 5651'),
(2, 2, '+63 917 649 5552'),
(3, 2, '+63 095 559 5453');

Third, let's create a query that will show the customer's name, the number of phones they have, and their phone list separated by a comma.

-- 3. Let's show the number of phone and phone list a customer have.
SELECT CONCAT(C1.[LastName], ', ', C1.[FirstName]) as [FullName],
       COUNT(C1.Id) as [Total Phone Number],
       STRING_AGG (P1.[PhoneNumber], ',') as [Phone List]
FROM #CustomersPhone P1
INNER JOIN #Customers C1 ON P1.UserId = C1.Id
GROUP BY C1.Id, C1.[LastName], C1.[FirstName]

HostForLIFEASP.NET SQL Server 2021 Hosting

 


 



SQL Server 2021 Hosting - HostForLIFE :: New String Function in SQL Server 2012

clock June 17, 2022 09:27 by author Peter

SQL Server 2012 introduced two new string functions: CONCAT and FORMAT. The CONCAT string function concatenates two or more strings into one string. CONCAT takes string arguments as input and concatenates these string inputs into a single string. It requires a minimum of two strings as input, otherwise it raises a compile time error. Here all arguments (inputs) are converted into a string type implicitly. A null value is implicitly converted into an empty string.
 
Syntax
CONCAT ( stringvalue1, stringvalue2 ,…, stringvalueN )
 
Argument / parameter
String Value:  A String value to concatenate with the other.
 
Example
--Example of simple string concatenation
SELECT CONCAT('Hi, ', 'I AM ', 'Peter' )


--Output
-- Hi, I AM Peter
--Example of NULL  string concatenation
SELECT CONCAT('Hello ', NULL, 'World' );

--Output
-- Hello World
--Example of other Data type  concatenation with string

SELECT CONCAT('Date : ', CAST(GETDATE() AS DATE));
--Date : 2013-09-25
SELECT CONCAT(123 + '.' + 45  );

--123.45

If all arguments are null then this function returns a string of type VARCAHR (1). The return type of this function depends on the arguments.
    If an argument is a SQL type NVARCHAR (MAX) or SQL CLR system type then the return type of this function is NVARCHAR (MAX)
    If an argument is VARBINARY (MAX) or VARCHAR (MAX) then the result type is VARCHAR (MAX) and if one of argument is NVARCHAR then the output is NVARCHAR (MAX).
    If an argument is NVARCHAR (<= 4000) than result  type is NVARCHAR (<= 4000)
    All other cases result in a type of VARCHAR (<=8000).
    When the length of the arguments are less than 4000 for NVARCHAR or less than 8000 for VARCHAR, implicit conversions can affect the length of the result type.

Other data types, like INT and FLOAT have different lengths when converted to a string. For example, an INT data type length is 12 when converted to a string, so the result of concatenating two integers has a length of 24.
 
FORMAT
The FORMAT string function returns a string formatted value with the specified format and culture (this is optional). We can use the FORMAT function for locale-aware formatting of a date and time and number values as a string.
 
Syntax
FORMAT (Value, Format , Culture)
 
Arguments / parameters
Value -  value in supported data type to format
Format - NVARCHAR format pattern. This argument must contain a valid .NET framework format string. Composite formatting is not supported. It is either a standard format string or a pattern for custom characters for dates and numeric values.
Culture - NVARCHAR Type specifies a culture.

A culture argument is optional, if we are not providing the culture value then the language of current session is used. The language can be set implicitly or explicitly (using a SET LANGUAGE statement). The culture argument accepts all cultures supported by the .NET Framework. It is not limited to the languages supported by SQL Server. If the culture argument is invalid then the Format string function throws an error.

Please refer to http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx to learn more about cultures supported by the .NET Framework.
 
Return Type is NVARCHAR or NULL
A FORMAT string function always returns NULL for an error when the culture is invalid. For the argument value, supported data types are numeric (like TINYINT, SMALLINT, INT, BIGINT, FLOAT, NUMERIC, DECIMAL, SMALLMONEY, MONEY and REAL) and date and time data type (like DATE, TIME, SMALLDATETIME, DATETIME, DATETIME2 and DATETIMEOFFSET). This function will not be remote and it depends on the presence of the Common Language Runtime (CLR).
 
Example
--Example of simple FORMAT string function
DECLARE @mydate DATETIME = '09/25/2013';
SELECT FORMAT ( @mydate, 'd', 'en-US' ) AS 'US Format'
,FORMAT ( @mydate, 'd', 'en-gb' ) AS 'GB Format'
--Output
--US Format         GB Format
----------------  -------------
--09/25/2013         25/09/2013
DECLARE @mydate DATETIME = '09/25/2013';
SELECT FORMAT ( @mydate, 'D', 'en-US' ) AS 'US Format'
,FORMAT ( @mydate, 'D', 'en-gb' ) AS 'GB Format'

--Output
--US Format GB Format
--Wednesday,September 25, 2013      25 September 2013  
--Example of custom formatting string
DECLARE @mydate DATETIME = '09/25/2013';

SELECT FORMAT ( @mydate, 'dd/MM/yyyy', 'en-US' )
--Output
--25/09/2013

SELECT FORMAT(555230655,'###-##-####')
--Output
--555-23-0655
--Example of formatting numeric type
SELECT FORMAT (8875.644 , 'C' ,  'en-US' ) AS 'Currency Format1'
,FORMAT (8875.644 , 'C0',  'en-US' ) AS 'Currency Format2'


Output
-- Currency Format1         Currency Format2      
  $8,875.64                        $8,876

 
These two newly introduced functions are very useful. The CONCAT string function is useful to concatenate two or more values and values of one or more data types. The FORMAT string function gets a formatted value with the specified format and optional culture.

HostForLIFEASP.NET SQL Server 2021 Hosting

 



SQL Server 2021 Hosting - HostForLIFE :: Format Date And Time In SQL Server Using FORMAT Function

clock June 13, 2022 09:06 by author Peter

In this article, you will learn how to Format Dates in SQL Server.
Here we will use the “FORMAT” function to format a date in SQL Server

Prerequisites

    Install SQL Server
    Install SQL Server Management Studio (SSMS)

For the above prerequisites, you can follow the article How to Install SQL Server and SQL Server Management Studio (SSMS)

Currently, I have installed SQL Server 2019 and SQL Server Management Studio 18.10 (SSMS) on my windows 11 machine.
Built-in function in SQL Server to get the DateTime value in a specific format

By using some built-in function in SQL Server we can get the DateTime value in a specific format.

For example,

GETDATE()
It returns server DateTime in “YYYY-MM-DD HH:mm:ss.fff” format.

SELECT GETDATE() AS [GETDATE()]
Result:-2022-06-09 12:28:37.787

GETUTCDATE()

It returns DateTime in GMT.

SELECT GETUTCDATE() AS [GETDATE()];
Result:-2022-06-09 07:10:54.350

SYSDATETIME()
It returns the server’s DateTime

SELECT SYSDATETIME() AS [GETDATE()];
Result:2022-06-09 12:41:46.8713228

SYSDATETIMEOFFSET()

It returns the server’s DateTime with time zone in which SQL Server instance is running.

SELECT SYSDATETIMEOFFSET() AS [GETDATE()];
Result:2022-06-09 12:42:15.7936382 +05:30

SYSUTCDATETIME()
It returns server DateTime in GMT.

SELECT SYSUTCDATETIME() AS [GETDATE()];
Result:2022-06-09 07:12:54.4664815

CURRENT_TIMESTAMP
It returns current DateTime of the server.

SELECT CURRENT_TIMESTAMP AS [GETDATE()];
Result:2022-06-09 12:43:40.650

After the CONVERT function, SQL Server added a function (FORMAT) to handle date formatting, giving us a new way to format dates in SQL Server.

To format the date and time data types from a date column (Date, DateTime, etc. Data type) in a table or a variant such as GETDATE(), use the FORMAT function.
Date Format with FORMAT Function

We have many ways to format dates as given below
DD/MM/YYYY
SELECT FORMAT (getdate(), 'dd/MM/yyyy ') as date;
Result:09/06/2022


DD/MM/YYYY, HH:MM:SS
SELECT FORMAT (getdate(), 'dd/MM/yyyy, hh:mm:ss ') as date;
Result:09/06/2022, 04:56:44

DDDD,MMMM,YYYY
SELECT FORMAT (getdate(), 'dddd, MMMM, yyyy') as date;
Result:Thursday, June, 2022

MMM DD YYYY
SELECT FORMAT (getdate(), 'MMM dd yyyy') as date;
Result:Jun 09 2022

MM.DD.YY
SELECT FORMAT (getdate(), 'MM.dd.yy') as date;
Result:06.09.22


MM-DD-YY
SELECT FORMAT (getdate(), 'MM-dd-yy') as date;
Result:06-09-22

HH:MM:SS TT
SELECT FORMAT (getdate(), 'hh:mm:ss tt') as date;
Result:05:17:37 PM

MM/DD/YYYY (Standard: USA)
SELECT FORMAT (getdate(), 'd','us') as date;
Result:06/09/2022

YYYY-MM-DD HH:MM:SS TT
SELECT FORMAT (getdate(), 'yyyy-MM-dd hh:mm:ss tt') as date;
Result:2022-06-09 05:18:55 PM

YYYY.MM.DD HH:MM:SS T
SELECT FORMAT (getdate(), 'yyyy.MM.dd hh:mm:ss t') as date;
Result:2022.06.09 05:19:53 P

DDDD,MMM,YYYY in Spanish
SELECT FORMAT (getdate(), 'dddd, MMMM, yyyy','es-es') as date;
Result:jueves, junio, 2022

DDDD DD, MMMM,YYYY in Japanese
SELECT FORMAT (getdate(), 'dddd dd, MMMM, yyyy','ja-jp') as date;
Result:木曜日 09, 6月, 2022

Date Format with Culture
We can get regional formatting by using the culture option as shown below:

English-USA
SELECT FORMAT (getdate(), 'd', 'en-US') as date;
Result:6/10/2022

French-France
SELECT FORMAT (getdate(), 'd', 'fr-FR') as date;
Result:10/06/2022

French - Belgium
SELECT FORMAT (getdate(), 'd', 'fr-BE') as date;
Result:10-06-22

French - Canada
SELECT FORMAT (getdate(), 'd', 'fr-CA') as date;
Result:2022-06-10

Danish - Denmark
SELECT FORMAT (getdate(), 'MM.dd.yy') as date;
Result:06.10.22

Dari - Afghanistan
SELECT FORMAT (getdate(), 'd', 'prs-AF') as date;
Result:1401/3/20


Simplified Chinese
SELECT FORMAT (getdate(), 'd', 'zh-CN') as date;
Result:2022/6/10

Divehi - Maldives
SELECT FORMAT (getdate(), 'd', 'dv-MV') as date;
Result:10/06/22

Bosnian Latin
SELECT FORMAT (getdate(), 'd', 'bs-Latn-BA') as date;
Result:10. 6. 2022.

isiXhosa / Xhosa - South Africa
SELECT FORMAT (getdate(), 'd', 'xh-ZA') as date;
Result:2022-06-10

Hungarian - Hungary
SELECT FORMAT (getdate(), 'd', 'hu-HU') as date;
Result:2022. 06. 10.

Spanish - Bolivia
SELECT FORMAT (getdate(), 'd', 'es-bo') as date;
Result:10/6/2022

Here is a list of all CultureInfo codes along with country names and language.

Country Language CultureInfo Code
Afghanistan Pashto ps-AF
Dari prs-AF
Albania Albanian sq-AL
Algeria Arabic ar-DZ
Argentina Spanish es-AR
Armenia Armenian hy-AM
Australia English en-AU
Austria German de-AT
Bahrain Arabic ar-BH
Bangladesh Bengali bn-BD
Basque Basque eu-ES
Belarus Belarusian be-BY
Belgium French fr-BE
Dutch nl-BE
Belize English en-BZ
Bolivarian Republic of Venezuela Spanish es-VE
Bolivia Quechua quz-BO
Spanish es-BO
Brazil Portuguese pt-BR
Brunei Darussalam Malay ms-BN
Bulgaria Bulgarian bg-BG
Cambodia Khmer km-KH
Canada French fr-CA
English en-CA
Caribbean English en-029
Catalan Catalan ca-ES
Chile Mapudungun arn-CL
Spanish es-CL
Colombia Spanish es-CO
Costa Rica Spanish es-CR
Croatia Croatian hr-HR
Cyrillic, Azerbaijan Azeri az-Cyrl-AZ
Cyrillic, Bosnia and Herzegovina Serbian sr-Cyrl-BA
Cyrillic, Bosnia and Herzegovina Bosnian bs-Cyrl-BA
Cyrillic, Mongolia Mongolian mn-MN
Cyrillic, Montenegro Serbian sr-Cyrl-ME
Cyrillic, Serbia Serbian sr-Cyrl-RS
Cyrillic, Serbia and Montenegro (Former Serbian ) sr-Cyrl-CS
Cyrillic, Tajikistan Tajik tg-Cyrl-TJ
Cyrillic, Uzbekistan Uzbek uz-Cyrl-UZ
Czech Republic Czech cs-CZ
Denmark Danish da-DK
Dominican Republic Spanish es-DO
Ecuador Quechua quz-EC
Spanish es-EC
Egypt Arabic ar-EG
El Salvador Spanish es-SV
Estonia Estonian et-EE
Ethiopia Amharic am-ET
Faroe Islands Faroese fo-FO
Finland Finnish fi-FI
Swedish sv-FI
Sami, Northern se-FI
Sami, Skolt sms-FI
Sami, Inari smn-FI
Former Yugoslav Republic of Macedonia Macedonian mk-MK
France French fr-FR
Breton br-FR
Occitan oc-FR
Corsican co-FR
Alsatian gsw-FR
Galician Galician gl-ES
Georgia Georgian ka-GE
Germany German de-DE
Upper Sorbian hsb-DE
Lower Sorbian dsb-DE
Greece Greek el-GR
Greenland Greenlandic kl-GL
Guatemala K'iche qut-GT
Spanish es-GT
Honduras Spanish es-HN
Hungary Hungarian hu-HU
Iceland Icelandic is-IS
India Hindi hi-IN
Bengali bn-IN
Punjabi pa-IN
Gujarati gu-IN
Oriya or-IN
Tamil ta-IN
Telugu te-IN
Kannada kn-IN
Malayalam ml-IN
Assamese as-IN
Marathi mr-IN
Sanskrit sa-IN
Konkani kok-IN
English en-IN
Indonesia Indonesian id-ID
Iran Persian fa-IR
Iraq Arabic ar-IQ
Ireland Irish ga-IE
English en-IE
Islamic Republic of Pakistan Urdu ur-PK
Israel Hebrew he-IL
Italy Italian it-IT
Jamaica English en-JM
Japan Japanese ja-JP
Jordan Arabic ar-JO
Kazakhstan Kazakh kk-KZ
Kenya Kiswahili sw-KE
Korea Korean ko-KR
Kuwait Arabic ar-KW
Kyrgyzstan Kyrgyz ky-KG
Lao P.D.R. Lao lo-LA
Latin, Algeria Tamazight tzm-Latn-DZ
Latin, Azerbaijan Azeri az-Latn-AZ
Latin, Bosnia and Herzegovina Croatian hr-BA
Latin, Bosnia and Herzegovina Bosnian bs-Latn-BA
Latin, Bosnia and Herzegovina Serbian sr-Latn-BA
Latin, Canada Inuktitut iu-Latn-CA
Latin, Montenegro Serbian sr-Latn-ME
Latin, Nigeria Hausa ha-Latn-NG
Latin, Serbia Serbian sr-Latn-RS
Latin, Serbia and Montenegro (Former Serbian ) sr-Latn-CS
Latin, Uzbekistan Uzbek uz-Latn-UZ
Latvia Latvian lv-LV
Lebanon Arabic ar-LB
Libya Arabic ar-LY
Liechtenstein German de-LI
Lithuania Lithuanian lt-LT
Luxembourg Luxembourgish lb-LU
German de-LU
French fr-LU
Malaysia Malay ms-MY
English en-MY
Maldives Divehi dv-MV
Malta Maltese mt-MT
Mexico Spanish es-MX
Mohawk Mohawk moh-CA
Monaco French fr-MC
Morocco Arabic ar-MA
Nepal Nepali ne-NP
Netherlands Dutch nl-NL
Frisian fy-NL
New Zealand Maori mi-NZ
English en-NZ
Nicaragua Spanish es-NI
Nigeria Yoruba yo-NG
Igbo ig-NG
Norway Norwegian, Bokmål nb-NO
Sami, Northern se-NO
Norwegian, Nynorsk nn-NO
Sami, Lule smj-NO
Sami, Southern sma-NO
Oman Arabic ar-OM
Panama Spanish es-PA
Paraguay Spanish es-PY
Peru Quechua quz-PE
Spanish es-PE
Philippines Filipino fil-PH
Poland Polish pl-PL
Portugal Portuguese pt-PT
PRC Tibetan bo-CN
Yi ii-CN
Uyghur ug-CN
Puerto Rico Spanish es-PR
Qatar Arabic ar-QA
Republic of the Philippines English en-PH
Romania Romanian ro-RO
Russia Russian ru-RU
Tatar tt-RU
Bashkir ba-RU
Yakut sah-RU
Rwanda Kinyarwanda rw-RW
Saudi Arabia Arabic ar-SA
Senegal Wolof wo-SN
Simplified, PRC Chinese zh-CN
Simplified, Singapore Chinese zh-SG
Singapore English en-SG
Slovakia Slovak sk-SK
Slovenia Slovenian sl-SI
South Africa Setswana tn-ZA
isiXhosa xh-ZA
isiZulu zu-ZA
Afrikaans af-ZA
Sesotho sa Leboa nso-ZA
English en-ZA
Spain, International Sort Spanish es-ES
Sri Lanka Sinhala si-LK
Sweden Swedish sv-SE
Sami, Northern se-SE
Sami, Lule smj-SE
Sami, Southern sma-SE
Switzerland Romansh rm-CH
German de-CH
Italian it-CH
French fr-CH
Syllabics, Canada Inuktitut iu-Cans-CA
Syria Syriac syr-SY
Syria Arabic ar-SY
Thailand Thai th-TH
Traditional Mongolian, PRC Mongolian mn-Mong-CN
Traditional, Hong Kong S.A.R. Chinese zh-HK
Traditional, Macao S.A.R. Chinese zh-MO
Traditional, Taiwan Chinese zh-TW
Trinidad and Tobago English en-TT
Tunisia Arabic ar-TN
Turkey Turkish tr-TR
Turkmenistan Turkmen tk-TM
U.A.E. Arabic ar-AE
Ukraine Ukrainian uk-UA
United Kingdom Welsh cy-GB
Scottish Gaelic gd-GB
English en-GB
United States English en-US
Spanish es-US
Uruguay Spanish es-UY
Vietnam Vietnamese vi-VN
Yemen Arabic ar-YE
Zimbabwe English en-ZW

As you saw above, we have used a lot of options for date and time formatting, which are detailed below,

  • hh - this is the hour from 01-12
  • HH - this is the hour from 00-23
  • mm - this is the minute from 00-59
  • ss - this is the second from 00-59
  • dd - this is day of month from 01-31
  • dddd - this is the day spelled out
  • MM - this is the month number from 01-12
  • MMM - month name abbreviated
  • MMMM - this is the month spelled out
  • yy - this is the year with two digits
  • yyyy - this is the year with four digits
  • tt - this shows either AM or PM
  • d - this is day of month from 1-31 (if this is used on its own it will display the entire date)
  • us - this shows the date using the US culture which is MM/DD/YYYY

HostForLIFEASP.NET SQL Server 2021 Hosting

 

 



SQL Server 2021 Hosting - HostForLIFE :: Difference Between SQL And NoSQL

clock June 10, 2022 09:45 by author Peter

1. Relational vs. non-relational

  • SQL databases are relational while NoSQL databases are non-relational.
  • A relational database is a digital database based on the relational model of data.
  • A non-relational database is not based on the traditional table structure that you may be used to. Instead, it is based on a more flexible model that can be adapted to fit the needs of the application.

2. Data schemas

  • SQL databases use a predefined schema and structured query language.
  • NoSQL databases have dynamic schemas that can accommodate unstructured data, which is often stored in a variety of ways.

3. Scaling

  • SQL databases are known for their ability to scale vertically in most situations.
  • It means you can increase the performance by adding more resources like CPU, RAM, or faster hard drives.
  • NoSQL databases are able to scale horizontally, meaning they can handle an increased workload by adding more servers.

4. Data structure

  • SQL databases store data in tables.
  • NoSQL databases are usually a document or key-value stores.

5. Use cases

  • SQL databases are the best choice for complex queries. If the data integrity and transactions are the requirements the SQL is better than NoSQL.
  • If you're working with constantly changing data structures or JSON data, NoSQL could be a better choice.

HostForLIFEASP.NET SQL Server 2021 Hosting

 



SQL Server 2021 Hosting - HostForLIFE :: How To Configure SMTP O365 Migration Using TLS 1.2 For SQL Database Mail?

clock June 8, 2022 10:06 by author Peter

This article will explain to you how exactly you need to configure TLS 1.2 as a default protocol and setup SMTP O365 migration with Database mail using SQL 2012 and above versions for Windows Server 2012 and above.

Common SMTP exceptions we usually faced

The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 2. Exception Message: Cannot send mails to mail server. (Failure sending mail.). )

Just follow the steps. The below steps are verified, proven, and compatible with the below servers and SQL versions,
    Windows Server 2012 R2 – SQL Server 2014 SP3
    Windows Server 2012 R2 – SQL Server 2012
    Windows Server 2016 – SQL Server 2016
    Windows Server 2016 – SQL Server 2017 and above.

Step 1

Check if your .NET framework is 4.6 or above, especially for SQL 2014/2016 version. Otherwise, install the latest .Net version. To verify the current version, open PowerShell, and run as administrator. Copy and execute the below command

reg query "HKLM\SOFTWARE\Microsoft\Net Framework Setup\NDP\v4" /s

Step 2
Check if .NET 3.5 was installed (You can skip this installation for SQL Server 2017, but the .Net framework installation must be .Net 4.8 or above)

Powershell command to list out the installed.NET versions - Run as admin
gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP’ -recurse | gp -name Version -EA 0 | where { $_.PSChildName -match ‘^(?!S)\p{L}’} | select PSChildName, Version

If not installed, either install 3.5 or place a config file in Binn folder
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn\DatabaseMail.exe.config

Place the XML content
<?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup useLegacyV2RuntimeActivationPolicy="true">
            <supportedRuntime version="v4.0"/>
            <supportedRuntime version="v2.0.50727"/>
        </startup>
    </configuration>

Save file as DatabaseMail.exe.config, with UTF-8 and saved in config format
MSSQL13/14/15 – Version depends on the SQL server installed. Forex: MSSQL13 – 2014 and MSSQL14-2016

Step 3
Install the Database mail advanced configuration. Execute the first query
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE
GO

Step 4
Enable the Windows firewall in the Azure portal under networking for VM
Add a rule in Inbound port rules and Outbound port rules with the highest priority by enabling the recommended port 587 with TCP protocol

Step 5
Enable the TLS 1.2 by adding/updating the registry Keys under Regedit. Click on start and type registry editor, run as admin, go to the respective Path and add the key(folder) and (DWord 32-bit) value

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727]
"DefaultSecureProtocols"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\.NETFramework\\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\.NETFramework\\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\SSL 2.0\\Client]
"DisabledByDefault"=dword:00000001

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\TLS 1.2\\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\TLS 1.2\\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\WinHttp]
"DefaultSecureProtocols"=dword:00000800

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Internet Settings\WinHttp]
"DefaultSecureProtocols"=dword:00000800

NOTE: Make sure you add only the pre-defined registry keys. Any typo error will stop the registry functions instantly. Copy and paste exactly the same.

Step 6
Configure SQL Database mail with account Name, Email-address [email protected], Server Name, PORT, Enable SSL, and Basic Auth

Step 7
Restart the machine and try the Database mail. If this does not work, add the below registry keys

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\SSL 2.0\\Client]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\SSL 2.0\\Server]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\SSL 3.0\\Client] #apply only if the registry key (SSL 3.0) is present
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\SSL 3.0\\Server] #apply only if the registry key(SSL 3.0) is present
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\TLS 1.0\\Client]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\TLS 1.0\\Server]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\TLS 1.1\\Client]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols\\TLS 1.1\\Server]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

Step 8
Restart again and Check if the TLS 1.2 is enabled through PowerShell. Copy, paste, and execute

$key = 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client\'
if (Test-Path $key) {
  $TLS12 = Get-ItemProperty $key
  if ($TLS12.DisabledByDefault -ne 0 -or $TLS12.Enabled -eq 0) {
    Throw "TLS 1.2 Not Enabled"
  }
  else{
 "TLS is enabled"
  }
}


Step 9
Execute the PowerShell and check if the email has triggered. Change values for $From - (Domain Account), $To - (User Account) , $Email.Credentials - (Domain Account and Password) variables
#Email Information
$From = "[email protected]"
$To = "[email protected]"
$Subject = "Test authenticated O365 smtp email"
$Body = "Test smtp email sent through Office 365's smtp relay."
#SMTP Relay Settings
$SMTP = "smtp.office365.com"
$Port = 587
$Email = New-Object Net.Mail.SmtpClient($SMTP, $Port)
$Email.EnableSsl = $true
$Email.Credentials = New-Object System.Net.NetworkCredential("[email protected]", "Add Password")
$Email.Send($From, $To, $Subject, $Body)


Step 10
Send test email from step-6 Database mail

Step 11
Execute the below SQL query and verify your email has been sent
select top 10 * from msdb.dbo.sysmail_sentitems order by send_request_date desc;
select top 10 * from msdb.dbo.sysmail_event_log order by log_date desc;

Step 12
If you are still struggling with the email, then the issue is probably in the Exchange Center. To resolve that, log in to the O365 and go to the Microsoft 365 Admin Center, select Users and follow the steps

Go to the Active User([email protected]) and select Manage Email Apps under the Mail tab and enable IMAP, POP, and Authenticated SMTP and execute the Powershell or Database mail test email and see the magic :-)

HostForLIFEASP.NET SQL Server 2021 Hosting

 



SQL Server 2021 Hosting - HostForLIFE :: SQL's Choose Function

clock June 7, 2022 10:00 by author Peter

In some cases, using the CASE statement can lead to numerous conditions. You may agree or not; these multiple conditions will look extensive and lengthy in some situations. Moreover, it can be challenging to maintain because of its complexity.

That's why in this post, we'll explore CHOOSE function. It helps developers have a better alternative to the CASE statement when simplifying lengthy conditions.
What's CHOOSE Function in SQL Server?

    Introduced in SQL Server 2012
    A function returns a specific value from a list based on its number index.
    It looks like an array, but the index starts from 1.

Syntax
CHOOSE (INDEX, VALUE1, VALUE2, VALUE3, VALUE4...)

Index
This is the element's position we seek in the output. Remember that CHOOSE doesn't use a zero-based index strategy (meaning the first item starts with 1). If in case the index is not an integer, SQL converts it to an integer otherwise returns NULL.

Values
It is a comma-separated list of any data type. Returns an item based on the index specified in the first(index) parameter.
Examples
 
1. Item index starts at 1
--Let's just say we wanted to list our favorite programming languages

--output: JavaScript
SELECT CHOOSE (1, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: Python
SELECT CHOOSE (2, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C#
SELECT CHOOSE (3, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C++
SELECT CHOOSE (4, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C
SELECT CHOOSE (5, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'


Output


2. When CHOOSE Function Returns NULL
--output: NULL
SELECT CHOOSE (0, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'

--output: NULL
SELECT CHOOSE (6, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'


Output


If we have passed the index outside the value list range, you'll be getting NULL as the return value.

3. Using Float or Decimal as Index Values
--output: NULL
SELECT CHOOSE (0.10, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: JavaScript
SELECT CHOOSE (1.10, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: Python
SELECT CHOOSE (2.23, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C#
SELECT CHOOSE (3.9923423, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C++
SELECT CHOOSE (4.7412122, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C
SELECT CHOOSE (5, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: NULL
SELECT CHOOSE (6.636, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'


Output


In our example above, we have seen that once we have passed a float or decimal data type, the value is implicitly converted into an integer as long as it's not int. We'll have the same output as from the first two examples.

4. Using String as Index-values
In this section, you'll see that we can still pass a string that has an integer value.

Let's see an example below.

--Let's just say we wanted to list our favorite programming languages
-- This time around, we'll use string but with a correct integer index
--output: JavaScript
SELECT CHOOSE ('1', 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: Python
SELECT CHOOSE ('2', 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C#
SELECT CHOOSE ('3', 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C++
SELECT CHOOSE ('4', 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C
SELECT CHOOSE ('5', 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'

Output

However, if we pass a non-integer value like an alphanumeric value or decimal value, it will throw an exception.

Let's see an example below.

--output: exception
SELECT CHOOSE ('One', 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: exception
SELECT CHOOSE ('1.15', 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'


5. Using CHOOSE in a SELECT Statements
This time, we'll be using the AdventureWorks database and trying to see the employees' birth months. By the way, we'll be using two tables [HumanResources].[Employee] and [Person].[Person] for us to get the names of the employees and show the birth months.

Let's see the example below.
SELECT
    FORMATMESSAGE('%s, %s %s',
                    P.[LastName],
                    P.[FirstName],
                    ISNULL(P.[MiddleName], '')) AS  [FullName],
    E.[BirthDate],
    CHOOSE(MONTH(E.[BirthDate]),  'Jan.',
                                'Feb.',
                                'Mar.',
                                'Apr.',
                                'May.',
                                'Jun.',
                                'Jul.',
                                'Aug.',
                                'Sep',
                                'Oct.',
                                'Nov.',
                                'Dec.') as [Birth Month]
  FROM
  [AdventureWorks2019].[HumanResources].[Employee] E
  INNER JOIN [Person].[Person] P ON
  E.[BusinessEntityID] = P.[BusinessEntityID]

HostForLIFEASP.NET SQL Server 2021 Hosting



SQL Server 2021 Hosting - HostForLIFE :: IIF and Choose Functions in SQL Server 2012

clock May 31, 2022 08:59 by author Peter

Here, I have provided an article showing you how to utilize the two new logical functions Choose and IIF in SQL Server. The Choose function works like an array kind of thing and the IIF function is used to check a condition. In this article we will see both functions with examples. These functions are also called new logical functions in SQL Server 2012. So let's take a look at a practical example of how to use the Choose and IIF functions in SQL Server. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

These are the two logical functions:
    IIF() Function
    Choose() Function

IIF() Function
The IIF function is used to check a condition. Suppose X>Y. In this condition a is the first expression and b is the second expression. If the first expression evaluates to TRUE then the first value is displayed, if not the second value is displayed.

Syntax
IIF ( boolean_expression, true_value, false_value )

Example
DECLARE @X INT;
SET @X=50;
DECLARE @Y INT;
SET @Y=60;
Select iif(@X>@Y, 50, 60) As IIFResult


In this example X=50 and Y=60; in other words the condition is false.  Select iif(@X>@Y, 50, 60) As IIFResult. It returns false value that is 60.

Output

Choose() Function
This function is used to return the value out of a list based on its index number. You can think of it as an array kind of thing. The Index number here starts from 1.

Syntax
CHOOSE ( index, value1, value2.... [, valueN ] )
CHOOSE() Function excepts two parameters,


Index: Index is an integer expression that represents an index into the list of the items. The list index always starts at 1.

Value: List of values of any data type.

Now some facts related to the Choose Function

1. Item index starts from 1
DECLARE @ShowIndex INT;
SET @ShowIndex =5;
Select Choose(@ShowIndex, 'M','N','H','P','T','L','S','H') As ChooseResult

In the preceding example we take index=5. It will start at 1. Choose() returns T as output since T is present at @Index location 5.

Output

2.  When passed a set of types to the function it returns the data type with the highest precedence; see:
DECLARE @ShowIndex INT;
SET @ShowIndex =5;
Select Choose(@ShowIndex ,35,42,12.6,14,15,18.7)  As CooseResult

In this example we use index=5. It will start at 1. Choose() returns 15.0 as output since 15 is present at @ShowIndex location 5 because in the item list, fractional numbers have higher precedence than integers.

3. If an index value exceeds the bound of the array it returns NULL
DECLARE @ShowIndex INT;
SET @ShowIndex =9;

Select Choose(@ShowIndex , 'M','N','H','P','T','L','S','H') 
As CooseResult

In this example we take index=9. It will start at 1. Choose() returns Null as output because in the item list the index value exceeds the bounds of the array; the last Index=8.

Output

4. If the index value is negative then that exceeds the bounds of the array therefore it returns NULL; see:
DECLARE @ShowIndex INT;

SET @ShowIndex =-1;


Select Choose(@ShowIndex, 'M','N','H','P','T','L','S','H')
  As CooseResult

In this example we take index= -1. It will start at 1. Choose() returns Null as output because in the item list the index value exceeds the bounds of the array.

Output

5. If the provided index value has a float data type other than int, then the value is implicitly converted to an integer; see:
DECLARE @ShowIndex  INT;

SET @ShowIndex =4.5;

Select Choose(@ShowIndex ,35,42,12.6,13,15,20)
As CooseResult

In this example we take index= 4.5. It will start at 1.  If the specified index value has a float data type other than int, then the value is implicitly converted to an integer. It returns the 13.0 as output since 15 is present at @ShowIndex=4.5 which means index is 4.

Output



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