European Windows 2019 Hosting BLOG

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

SQL Server Hosting - HostForLIFE :: Insert Data Into SQL Server Table Using PowerShell

clock July 7, 2021 06:30 by author Peter

In this blog, we will create a PowerShell script that inserts the data into a SQL table. In this scenario, we have one SQL table of student details. We insert the Student name, standard, and division into the ‘Student’ table. Here we have the ‘Student’ table in SQL Server. We have two different columns ‘Name’, ‘STD’. We will enter the 5 static details of students.

Let’s get started!
We will define the variables. We have 5 variables ‘serverName’, ‘databaseName’, ‘tableName’, ‘studentName’ and ‘standard’. 

$serverName = "HostForLIFE"
$databaseName = "StudentDetails"
$tableName = "dbo.Student"
$studentName = 'John','Debo','Carry','Mini'
$standard = '5'

We will establish a new connection for the SQL Server database using the below code. We will use the ‘ServerName’ and ‘databaseName’ for establishing the connection string.
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection


We will apply for each student’s name and execute the command for inset into the SQL table. Here we use into query command and execute the command. This query will insert the employee name and standard field in the student table.

foreach($Name in $studentName){
  $insertquery="
  INSERT INTO $tableName
      ([Name],[STD])
    VALUES
      ('$Name','$standard')"
  $Command.CommandText = $insertquery
  $Command.ExecuteNonQuery()
}


Close the connection of SQL.
$Connection.Close();

Here is the whole code for inserting the data into the table.
$serverName = "HostForLIFE"
$databaseName = "StudentDetails"
$tableName = "dbo.Student"
$studentName = 'John','Debo','Carry','Mini'
$standard = '5'
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
foreach($Name in $studentName){
  $insertquery="
  INSERT INTO $tableName
      ([Name],[STD])
    VALUES
      ('$Name','$standard')"
  $Command.CommandText = $insertquery
  $Command.ExecuteNonQuery()
}
$Connection.Close();


Output

HostForLIFEASP.NET SQL Server 2019 Hosting





SQL Server Hosting - HostForLIFE :: Most Important SQL Commands

clock June 28, 2021 06:45 by author Peter

In this article, we will learn about the important SQL commands with explanation which are commonly used in every project. Let's start with these commands,
DDL Commands
 
CREATE TABLE
Using CREATE TABLE you can create a new table in the database. You can set the table name and column name in the table.
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);

SQL
ALTER TABLE


The ALTER TABLE is used to add, delete, or modify columns in a table.

ALTER TABLE table_name
ADD column_name datatype;


SQL
DROP Table


The DROP TABLE is used to drop an existing table in a database.
DROP TABLE table_name;

SQL
TRUNCATE Table


The SQL TRUNCATE TABLE command is used to delete complete data from an existing table.

TRUNCATE TABLE table_name;

SQL
COMMENT


When we do not want our code to be executed we comment them.

There are three types of comment in SQL,
    Single line comments.
    Multi-line comments
    Inline comments

Single line comments
-- single line comment example
SELECT * FROM employees;


Lua
Multi-line comments

/* multi line comment line 1
line 2 */
SELECT * FROM employees;

SQL
Inline comments
SELECT * FROM /* employees; */

SQL
DML Commands
 
SELECT
SELECT statements are used to fetch data from a database. Every query will begin with SELECT.

SELECT column_name
FROM table_name;


SQL
INSERT
INSERT statements are used to add a new row to a table.

INSERT INTO table_name (column_1, column_2, column_3)
VALUES (value_1, 'value_2', value_3);


SQL
UPDATE


UPDATE statements allow you to edit rows in a table.

UPDATE table_name
SET column_name = new_value
WHERE column_name = old_value;


SQL
DELETE

DELETE statements are used to remove rows from a table.
DELETE FROM table_name
WHERE column_name = column_value;


SQL
DCL Commands

GRANT
GRANT used to provide access or privileges on the database objects to the users.
GRANT privileges ON object TO user;

SQL
REVOKE

REVOKE command removes user access rights or privileges to the database objects.
REVOKE privileges ON object FROM user;

SQL
TCL Commands

COMMIT

COMMIT is used to save changes by a transaction to the database.

COMMIT;

SQL
ROLLBACK

The ROLLBACK command is used to undo transactions that have not saved to the database. The command is only be used to undo changes since the last COMMIT.
ROLLBACK;

SQL
SAVEPOINT

SAVEPOINT command is used to temporarily save a transaction to a point so that you can rollback to that point whenever required.

SAVEPOINT SAVEPOINT_NAME;


SQL
Other Useful Commands

 
AND

And is used to combines two conditions. Both conditions must be true to display the record.

SELECT column1, column2
FROM table_name
WHERE condition1 AND condition2;


SQL
AS

With the help of AS you can rename a column or table using an alias.

SELECT column_name AS 'Alias_Example'
FROM table_name;


SQL
AVG()

AVG() function returns the average value of a numeric column.

SELECT AVG(column_name)
FROM table_name;


SQL
BETWEEN

BETWEEN operator selects values (values can be numbers, text, or dates) within a given range.

SELECT column1
FROM table_name
WHERE column1 BETWEEN value1 AND value2;


SQL
CASE

In SQL we are using CASE like an if-then-else statement.

SELECT column_name,
  CASE
    WHEN condition THEN 'Result1'
    WHEN condition THEN 'Result2'
    ELSE 'Result3'
  END
FROM table_name;


SQL
COUNT()

The COUNT() function returns the number of rows in a column.
SELECT COUNT(column_name)
FROM table_name;


SQL
GROUP BY

The GROUP BY statement groups rows that shows the identical data into groups.

SELECT column_name1, column_name2
FROM table_name
GROUP BY column_name1;

SQL
HAVING

WHERE keyword cannot be used with aggregate functions that's why the HAVING clause was added to SQL.

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition;

SQL
INNER JOIN

An inner join will combine rows that have matching values in both tables.
SELECT column_name
FROM table1
INNER JOIN table2
On table1.column_name = table2.column_name;

SQL
IS NULL / IS NOT NULL

We used IS NULL and IS NOT NULL with the WHERE clause to test the value empty or not.

IS NULL Syntax,

SELECT column_name
FROM table_name
WHERE column_name IS NULL;

SQL

IS NOT NULL Syntax,

SELECT column_name
FROM table_name
WHERE column_name IS NOT NULL;


SQL
LIKE

LIKE is a special operator used to search for a specific pattern in a column with the WHERE clause.

SELECT column_name
FROM table_name
WHERE column_name LIKE pattern;


SQL
MAX()

MAX() is a function that returns the largest value in that column.

SELECT MAX(column_name)
FROM table_name;


SQL
MIN()


MIN() is a function that returns the smallest value in that column.

SELECT MIN(column_name)
FROM table_name;

SQL
OR

The OR operator displays the result where one of two conditions is true.

SELECT column1, column2
FROM table_name
WHERE condition1 OR condition2;


SQL
ORDER BY

ORDER BY is used to sort the result in ascending or descending order. By default, it sorts the records in ascending order for descending order, we will use the DESC keyword.
SELECT column_name
FROM table_name
ORDER BY column_name ASC | DESC;

SQL
ROUND()


The ROUND function returns a number rounded to a certain number of decimal places.
SELECT ROUND(column_name, integer)
FROM table_name;

SQL
SELECT DISTINCT


The SELECT DISTINCT statement is used to returns unique values in the specified column(s).
SELECT DISTINCT column_name
FROM table_name;

SQL
SUM


The SUM() function returns the total sum of a column.

SELECT SUM(column_name)
FROM table_name;


SQL
WHERE

WHERE clause is used to filter records.

SELECT column1, column2
FROM table_name
WHERE condition;

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: Group By, Having, and Where Clauses In SQL

clock June 21, 2021 08:25 by author Peter

In this blog, we will discuss how to work with GROUP BY, WHERE, and HAVING clauses in SQL and explain the concept with an example in a simple way. I hope this is very useful for beginners and intermediates to help them understand the basic concept.
 
Group by clause
The Group by clause is often used to arrange identical duplicate data into groups with a select statement to group the result-set by one or more columns. This clause works with the select specific list of items, and we can use HAVING, and ORDER BY clauses. Group by clause always works with an aggregate function like MAX, MIN, SUM, AVG, COUNT.
 
Let us discuss group by clause with an example. We have a VehicleProduction table and there are some models with a price and it has some duplicate data. We want to categorize this data in a different group with a respective total price.
 
Example

    Create table VehicleProduction    
    (    
    Id int primary key Identity,     
    Model varchar(50),    
    Price money    
    )    
        
    Insert into VehicleProduction values('L551', 850000),('L551', 850000),('L551', 850000),('L551', 750000),    
    ('L538', 650000),('L538', 650000),('L538', 550000),('L530', 450000),('L530',350000), ('L545', 250000)    
        
    Select * from VehicleProduction    

Output


Aggregate Functions
MAX()- function returns the maximum value of the numeric column of specified criteria.
 
Example
    Select max(Price) As 'MaximumCostOfModel' from VehicleProduction    

Output

MIN()- function returns the minimum of the numeric column of specified criteria.
 
Example
    Select Min(Price) As 'MinimumCostOfModel' from VehicleProduction    

Output

MIN()- function returns the minimum of the numeric column of specified criteria.
 
Example
    Select Min(Price) As 'MinimumCostOfModel' from VehicleProduction    

Output

SUM()- function returns the total sum of a numeric column of specified criteria.
 
Example
    Select SUM(Price) As 'SumCostOfAllModel' from VehicleProduction    

Output

AVG()- function returns the average value of a numeric column of specified criteria.
 
Example
    Select AVG(Price) As 'AverageCostOfModel' from VehicleProduction    

Output

COUNT()- function returns the number of rows that match specified criteria.
 
Example
    Select Count(Price) As 'TotalVehicleModels' from VehicleProduction    

Output

Distinct clause
The distinct clause is used to filter unique records out of the duplicate records that satisfy the query criteria.
 
Example
    Select Distinct(Model),  Price from VehicleProduction    

Output

Group by clause
The Group by clause is often used to arrange the identical duplicate data into groups with the select statement. This clause works with the select specific list of items, for that we can use HAVING, and ORDER BY clauses.
 
Syntax
    SELECT Column1, Column2    
    FROM TableName    
    GROUP BY Column1, Column2  
 

Example
    Select * from VehicleProduction     
     
    Select Model, Price from VehicleProduction     
    group by Model, Price    

Output

Let’s look at an example of a GROUP BY with aggregate functions.
 
GROUP BY with aggregate functions
Example
    Select Model, Price, Count(*) As QtyOfModel, Sum(Price) As TotPriceOfModel  from VehicleProduction     
    group by Model, Price  


Output


Where clause
Where clause works with select clause but won’t work on the group by or aggregate function condition.
 
Example 1
    Select Model, Price from VehicleProduction     
    where Model != 'L530'    
    group by Model, Price  

Output


Example 2
We can’t use where clause after group by clause

    Select Model, Price from VehicleProduction     
    group by Model, Price     
    where Model != 'L530'    


Output


Having clause
 
Having clause works with a group by clause but specifically works on aggregate function condition.
 
Example
    Select Model, Price from VehicleProduction     
    Group by Model, Price     
    Having SUM(Price)  > 600000.00   


Output


ORDER BY clause
Order By clause shows the records in ascending or descending order of the specific condition.
 
Example
    Select Model, Price from VehicleProduction     
    Group by Model, Price     
    Having SUM(Price)  > 400000.00     
    order by Price desc    


Output

I hope you understand the concept, please post your feedback, questions, or comments about this blog and feel free to tell me the required changes in this write-up to improve the content quality.

HostForLIFEASP.NET SQL Server 2019 Hosting


 



SQL Server Hosting - HostForLIFE :: Quick View Of Indexes In SQL Server

clock June 15, 2021 09:36 by author Peter

This section is all about Indexes in SQL Server. We will learn about indexes in SQL Server including how to create the index, rename index, drop index, and more.
INDEXES are Special Data Structures associated with tables or views that will help it to speed up the data fetching/ queries.
 
Indexes are similar to the index of a book/notebook. Whenever we want to search any topic, we refer to the index to find that page number to access quickly without going through all the pages of the book. Indexes in SQL Server works in the same manner, an index can be created with both tables and views.
 
SQL Server provides two types of indexes,

    Clustered index
    Non-clustered index

Let's explore more closely,
 
Clustered index
A clustered index stores data rows in a sorted structure based on its key values. This key is a column or a group of columns on which the sorting will be done. By default, the primary key of the table is used as the key for the clustered index.
 
A clustered index is a default phenomenon and there can be only one clustered index in a table because rows can be only sorted in one order.
 
How to create clustered index?
Syntax to create clustered index,
    CREATE CLUSTERED INDEX index_Name  
    on Schema_Name.table_name (Columns)   


Non-clustered index
A non-clustered index is a data structure that improves the speed of data retrieval from tables.
 
Non-clustered index sorts and stores data separately from the data rows in the table.
 
How to create clustered index?
Syntax to create non-clustered index,
    CREATE [NONCLUSTERED] INDEX index_Name  
    on Schema_Name.table_name (Columns) 
 

Some notable syntax,
 
How to check indexes for the mentioned table?
    EXEC SP_HELPINDEX 'schema_name.table_name';   

How to rename the indexes?
    EXEC SP_RENAME 'OldIndexName', 'NewIndexName', 'INDEX';   

How to drop indexes?
    DROP INDEX removes one or more indexes from the current database.  
    DROP INDEX [IF EXISTS] INDEX_NAME ON TABLE_NAME   

To summarize, what we have learned,
    INDEXES
    Types of Indexes
    How to Rename Indexes
    How to Drop Indexes

If you guys have any questions let me know.

HostForLIFEASP.NET SQL Server 2019 Hosting

 



European ASP.NET Ajax Hosting :: What is AJAX Security?

clock June 10, 2021 08:51 by author Peter

The advent of Web 2.0 brought about a new technique in building web applications, Asynchronous, JavaScript, and XML. AJAX is a faster and interactive technology that has found great favor among modern businesses today. With it comes a combination of JavaScript, HTML, CSS, and XML to build one useful technique that makes web application interactivity faster and affordable in terms of bandwidth consumption. This article is a description of AJAX and its security issues.
 
AJAX
Conventional web sites were known to be slower and consumed more bandwidth because of the way they connected to the server. It would take a page to reload to connect to the server using synchronous connection. This meant more bandwidth consumption and slower response from web applications. On the other hand, AJAX is a browser technology that uses asynchronous means to communicate to the server. This means that you can communicate with the server to update certain portions of a page without having to reload the whole page.
 
A good example of AJAX in use is the Google create account page which recognizes a username in use soon after a user enters their suggested username. This means that in the background the page has communicated with the Google server to check if the name exists and show results without having to reload the entire page.
 
It is considered the most feasible Rich Internet Application (RIA) to date. AJAX makes use of Open Standards that include HTML and CSS for the presentation of data, XML for data storage and transfers to and from the server, XMLHttpRequest objects in the browser to fetch data from the server, and finally JavaScript for interactivity. AJAX can also transfer data in JSON or plain-text.
 
Security Issues with AJAX
AJAX applications only use a different technique to connect to the server. However, they use the same security schemes to connect to the server. This entails that you still have to include your authentication, authorization, and data protection methods in the web.xml file or program. AJAX applications bear the same vulnerabilities as ordinary or conventional web applications. In as much as people prefer the swiftness and the advanced interactivity of AJAX applications, some are misled to believe that AJAX web applications are more secure than ordinary web applications.
 
AJAX applications are known to have session management vulnerabilities and a lot of loopholes in the hidden URLs which carry AJAX requests to the server.
 
The AJAX engine makes use of JavaScript to transfer user requests/commands and transforms them into function calls. The AJAX engine sends these function calls in plain-text to the server that may be intercepted by attackers to reveal database information, variable names, or any other confidential user data that may be used by the attacker maliciously.
 
AJAX-based applications are also vulnerable to Cross-Site Request Forgery (CRSF) and Cross-Site Scripting (XSS). Although it is not that easy to exploit CSRF on AJAX applications because the requests are hidden, attackers may be able to create a script that can steal a user’s session token and by so doing be able to steal the user’s session remotely.
 
This can be avoided by creating random complex tokens for the AJAX requests which are not identified by the attackers. The server embeds the complex token on the page and checks for it each time the users make a request to the server and if it is any different the server does not process the request.
 
To ensure AJAX security against XSS, the application has to strictly sanitize user input and output. The use of JS functions such as ‘document.write()’, ‘innerHTML()’, ‘eval()’, ‘write()’ may make it possible for XSS attacks in AJAX web applications.
 
Conclusion
AJAX is a very fast and affordable browser technology but needs to be treated just like any other web application when it comes to security. Organizations need to do thorough scanning of their AJAX applications just like on conventional web applications to ensure absolute security from common vulnerabilities.

HostForLIFEASP.NET Ajax Hosting

 



SQL Server Hosting - HostForLIFE :: Check If String Value Has Numeric Data Or Not In SQL

clock June 7, 2021 08:53 by author Peter

Herewith, I have shared my analysis and added the solutions. order to check the varchar field for the mathematical calculation whether the varchar field value has numeric data or not.
 
We are storing the numeric and string value in the varchar. For example, $500. If we use the Isnumeric, it will return true only. In order to avoid this kindly of mirror issue, we can use the try_Cast, It will return false only.
 
When string value has this character € | + | . | , | \ | - | 12e4 |
    isnumeric return result 1.
    When we using try_Cast it returns 0.


See below another example,
    $1000 is not numeric, but ISNUMERIC returns true, then proceed for the convert it as numeric.
    Now, It says "Error converting data type varchar to numeric"


SQL
    DECLARE @var varchar(100)   
    SET @var = '$1000' SELECT ISNUMERIC(@var)   
    SELECT CASE   
    WHEN ISNUMERIC (@var) = 1   
    THEN CAST(@var AS numeric(36, 4))   
    ELSE CAST('0' AS numeric(36,4))   
    END  


Result

Check String Value Has Numeric Data Or Not In SQL

ISNUMERIC Return the varchar as True Example


Solutions
 
In this type of case, while varchar value is used for numeric calculation. Use TRY_CAST
    DECLARE @var varchar(100);   
    SET @var = '$1000';  
    SELECT ISNULL( TRY_CAST(@var AS numeric(36, 4)), 0 )

 

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: Auto Query Generator In MSSQL Server

clock May 31, 2021 07:20 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.

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.

How could this Auto Query Generator benefit you?

    Minimizes your time in Query Creation
    Eliminates human errors in datatype mismatches, size etc.
    Irrespective of table size, you get all basic SQL instantly
    Especially comes in handy while dealing with a table that has hundreds of columns

I hope this article helps you. Please comment below, if you have any query on this article.

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: Check If String Value Has Numeric Data Or Not In SQL

clock May 25, 2021 08:04 by author Peter

Herewith, I have shared my analysis and added the solutions. order to check the varchar field for the mathematical calculation whether the varchar field value has numeric data or not.
 
We are storing the numeric and string value in the varchar. For example, $500. If we use the Isnumeric, it will return true only. In order to avoid this kindly of mirror issue, we can use the try_Cast, It will return false only.
 
When string value has this character € | + | . | , | \ | - | 12e4 |
    isnumeric return result 1.
    When we using try_Cast it returns 0.

See below another example,
    $1000 is not numeric, but ISNUMERIC returns true, then proceed for the convert it as numeric.
    Now, It says "Error converting data type varchar to numeric"

SQL
    DECLARE @var varchar(100)   
    SET @var = '$1000' SELECT ISNUMERIC(@var)   
    SELECT CASE   
    WHEN ISNUMERIC (@var) = 1   
    THEN CAST(@var AS numeric(36, 4))   
    ELSE CAST('0' AS numeric(36,4))   
    END  


Result

ISNUMERIC Return the varchar as True Example

HostForLIFEASP.NET SQL Server 2019 Hosting

 




SQL Server Hosting - HostForLIFE :: Computed Column In SQL Server

clock May 24, 2021 07:09 by author Peter

In this article, we will see what ‘Computed Column in SQL Server' is, and how we can use it.

First of all, what is a Computed column in SQL Server?
Computed column as the name gives an idea it's related to something calculation/ computation, yes, computed columns are similar to a column in Excel with an applied formula that calculates the value automatically of the given query or the columns.
 
Computed columns are columns with some user-defined expression or with some formula to calculate the corresponding columns with operators or with some query.
 
Let's take an example,
 
Creating a table named 'CalculationTable' with a computed column named 'Age',
    Create table CalculationTable  
    (  
       ID INT IDENTITY(1,1) PRIMARY KEY,  
       NAME NVARCHAR(50) null,  
       DATEOFBIRTH DATE null,  
       AGE AS (DATEDIFF(YEAR,DATEOFBIRTH,GETDATE()))  
    )  


You can also use the SSMS user interface to define that column (formula), let’s see how,

 
Now let's insert some data into the table,


In the above example, AGE is computed column, whenever we insert the value of DATEOFBIRTH then AGE will be calculated automatically.
 
I hope this will be helpful to understand the Computed Columns in SQL Server.
 
For practice, you can download the attached scripts.

HostForLIFEASP.NET SQL Server 2019 Hosting



SQL Server Hosting - HostForLIFE :: SQL Server How To Convert UTC Date To Any Given Timezone Name Date In SQL Server?

clock May 17, 2021 07:23 by author Peter

I would suggest storing the DateTime in the table as UTC(which is called Coordinated Universal Time). This time zone is a Standard Time Zone. To avoid timezone complexity in our application.
 
Herewith, I shared the step-by-step conversion of UTC Date to given Time Zone name date in the SQL Server.
 
Step 1
Create Time zone Table,
    CREATE TABLE  [Timezone](     
    [Id]            [int] NOT NULL PRIMARY KEY,    
      [Identifier]        [varchar](100) NULL,     
    [StandardName]        [varchar](100) NULL,  
       [DisplayName]       [varchar](100) NULL,  
       [DaylightName]        [varchar](100) NULL,    
     [SupportsDaylightSavingTime]  [bit] NULL,    
      [BaseUtcOffsetSec]      [int] NULL   
    )     

Step 2 - Insert Time Zone Name
Insert the below given query with 138 timezone with names,
    insert into Timezone values(1,  NULL,'UTC-11','(UTC-11:00) Coordinated Universal Time-11',NULL,0,-39600)    
    insert into Timezone values(2,  NULL,'Aleutian Standard Time','(UTC-10:00) Aleutian Islands',NULL,0,-36000)    
    insert into Timezone values(3,  NULL,'Hawaiian Standard Time','(UTC-10:00) Hawaii',NULL,0,-36000)    
    insert into Timezone values(4,  NULL,'Marquesas Standard Time','(UTC-09:30) Marquesas Islands',NULL,0,-34200)    
    insert into Timezone values(5,  NULL,'Alaskan Standard Time','(UTC-09:00) Alaska',NULL,0,-32400)    
    insert into Timezone values(6,  NULL,'UTC-09','(UTC-09:00) Coordinated Universal Time-09',NULL,0,-32400)    
    insert into Timezone values(7,  NULL,'Pacific Standard Time (Mexico)','(UTC-08:00) Baja California',NULL,0,-28800)    
    insert into Timezone values(8,  NULL,'UTC-08','(UTC-08:00) Coordinated Universal Time-08',NULL,0,-28800)    
    insert into Timezone values(9,  NULL,'Pacific Standard Time','(UTC-08:00) Pacific Time (US & Canada)',NULL,0,-28800)    
    insert into Timezone values(10,NULL,'US Mountain Standard Time','(UTC-07:00) Arizona',NULL,0,-25200)    
    insert into Timezone values(11,NULL,'Mountain Standard Time (Mexico)','(UTC-07:00) Chihuahua, La Paz, Mazatlan',NULL,0,-25200)    
    insert into Timezone values(12,NULL,'Mountain Standard Time','(UTC-07:00) Mountain Time (US & Canada)',NULL,0,-25200)    
    insert into Timezone values(13,NULL,'Central America Standard Time','(UTC-06:00) Central America',NULL,0,-21600)    
    insert into Timezone values(14,NULL,'Central Standard Time','(UTC-06:00) Central Time (US & Canada)',NULL,0,-21600  )    
    insert into Timezone values(15,NULL,'Easter Island Standard Time','(UTC-06:00) Easter Island',NULL,0,-21600 )    
    insert into Timezone values(16,NULL,'Central Standard Time (Mexico)','(UTC-06:00) Guadalajara, Mexico City, Monterrey',NULL,0,-21600    )    
    insert into Timezone values(17,NULL,'Canada Central Standard Time','(UTC-06:00) Saskatchewan',NULL,0,-21600 )    
    insert into Timezone values(18,NULL,'SA Pacific Standard Time','(UTC-05:00) Bogota, Lima, Quito, Rio Branco',NULL,0,-18000  )    
    insert into Timezone values(19,NULL,'Eastern Standard Time (Mexico)','(UTC-05:00) Chetumal',NULL,0,-18000)    
    insert into Timezone values(20,NULL,'Eastern Standard Time','(UTC-05:00) Eastern Time (US & Canada)',NULL,0,-18000  )    
    insert into Timezone values(21,NULL,'Haiti Standard Time','(UTC-05:00) Haiti',  NULL,0,-18000)    
    insert into Timezone values(22,NULL,'Cuba Standard Time','(UTC-05:00) Havana',NULL,0,-18000)    
    insert into Timezone values(23,NULL,'US Eastern Standard Time','(UTC-05:00) Indiana (East)',NULL,0,-18000   )    
    insert into Timezone values(24,NULL,'Turks And Caicos Standard Time','(UTC-05:00) Turks and Caicos',NULL,0,-18000   )    
    insert into Timezone values(25,NULL,'Paraguay Standard Time','(UTC-04:00) Asuncion',NULL,0,-14400)    
    insert into Timezone values(26,NULL,'Atlantic Standard Time','(UTC-04:00) Atlantic Time (Canada)',NULL,0,-14400 )    
    insert into Timezone values(27,NULL,'Venezuela Standard Time','(UTC-04:00) Caracas',NULL,0,-14400)    
    insert into Timezone values(28,NULL,'Central Brazilian Standard Time','(UTC-04:00) Cuiaba',NULL,0,-14400)    
    insert into Timezone values(29,NULL,'SA Western Standard Time'  ,'(UTC-04:00) Georgetown, La Paz, Manaus, San Juan',NULL,0,-14400   )    
    insert into Timezone values(30,NULL,'Pacific SA Standard Time','(UTC-04:00) Santiago',NULL,0,-14400)    
    insert into Timezone values(31,NULL,'Newfoundland Standard Time','(UTC-03:30) Newfoundland',NULL,0,-12600)    
    insert into Timezone values(32,NULL,'Tocantins Standard Time','(UTC-03:00) Araguaina',  NULL,0,-10800)    
    insert into Timezone values(33,NULL,'E. South America Standard Time','(UTC-03:00) Brasilia',NULL,0,-10800)    
    insert into Timezone values(34,NULL,'SA Eastern Standard Time'  ,'(UTC-03:00) Cayenne, Fortaleza',NULL,0,-10800 )    
    insert into Timezone values(35,NULL,'Argentina Standard Time','(UTC-03:00) City of Buenos Aires',NULL,0,-10800  )    
    insert into Timezone values(36,NULL,'Greenland Standard Time','(UTC-03:00) Greenland',NULL,0,-10800)    
    insert into Timezone values(37,NULL,'Montevideo Standard Time','(UTC-03:00) Montevideo',NULL,0,-10800   )    
    insert into Timezone values(38,NULL,'Magallanes Standard Time','(UTC-03:00) Punta Arenas',NULL,0,-10800 )    
    insert into Timezone values(39,NULL,'Saint Pierre Standard Time','(UTC-03:00) Saint Pierre and Miquelon',NULL,0,-10800  )    
    insert into Timezone values(40,NULL,'Bahia Standard Time','(UTC-03:00) Salvador',NULL,0,-10800  )    
    insert into Timezone values(41,NULL,'UTC-02','(UTC-02:00) Coordinated Universal Time-02',NULL,0,-7200   )    
    insert into Timezone values(42,NULL,'Mid-Atlantic Standard Time','(UTC-02:00) Mid-Atlantic - Old',NULL,0,-7200  )    
    insert into Timezone values(43,NULL,'Azores Standard Time','(UTC-01:00) Azores',NULL,0,-3600)    
    insert into Timezone values(44,NULL,'Cape Verde Standard Time','(UTC-01:00) Cabo Verde Is.',NULL,0,-3600)    
    insert into Timezone values(45,NULL,'UTC','(UTC) Coordinated Universal Time',NULL,0,0)    
    insert into Timezone values(46,NULL,'GMT Standard Time','(UTC+00:00) Dublin, Edinburgh, Lisbon, London',NuLL,0,0)    
    insert into Timezone values(47,NULL,'Greenwich Standard Time','(UTC+00:00) Monrovia, Reykjavik  ',NULL,0,0)    
    insert into Timezone values(48,NULL,'Sao Tome Standard Time','(UTC+00:00) Sao Tome',NULL,0,0)    
    insert into Timezone values(49,NULL,'W. Europe Standard Time','(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',NULL,0,+3600)    
    insert into Timezone values(50,NULL,'Central Europe Standard Time','(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',NULL,0,+3600)    
    insert into Timezone values(51,NULL,'Romance Standard Time','(UTC+01:00) Brussels, Copenhagen, Madrid, Paris',NULL,0,+3600)    
    insert into Timezone values(52,NULL,'Morocco Standard Time','(UTC+01:00) Casablanca',NULL,  0,+3600)    
    insert into Timezone values(53,NULL,'Central European Standard Time','(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb',NULL,0,+3600)    
    insert into Timezone values(54,NULL,'W. Central Africa Standard Time','(UTC+01:00) West Central Africa',NULL,0,+3600)    
    insert into Timezone values(55,NULL,'Jordan Standard Time','(UTC+02:00) Amman',NULL,0,+7200)    
    insert into Timezone values(56,NULL,'GTB Standard Time','(UTC+02:00) Athens, Bucharest',NULL,0,+7200)    
    insert into Timezone values(57,NULL,'Middle East Standard Time','(UTC+02:00) Beirut',NULL,0,+7200)    
    insert into Timezone values(58,NULL,'Egypt Standard Time','(UTC+02:00) Cairo',NULL,0,+7200)    
    insert into Timezone values(59,NULL,'E. Europe Standard Time','(UTC+02:00) Chisinau',NULL,0,+7200)    
    insert into Timezone values(60,NULL,'Syria Standard Time','(UTC+02:00) Damascus',NULL,0,+7200)    
    insert into Timezone values(61,NULL,'West Bank Standard Time','(UTC+02:00) Gaza, Hebron',NULL,0,+7200)    
    insert into Timezone values(62,NULL,'South Africa Standard Time','(UTC+02:00) Harare, Pretoria',NULL,0,+7200)    
    insert into Timezone values(63,NULL,'FLE Standard Time','(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius',NULL,0,+7200)    
    insert into Timezone values(64,NULL,'Israel Standard Time','(UTC+02:00) Jerusalem',NULL,0,+7200)    
    insert into Timezone values(65,NULL,'Kaliningrad Standard Time','(UTC+02:00) Kaliningrad',NULL,0,+7200)    
    insert into Timezone values(66,NULL,'Sudan Standard Time','(UTC+02:00) Khartoum',NULL,0,+7200)    
    insert into Timezone values(67,NULL,'Libya Standard Time','(UTC+02:00) Tripoli',NULL,0,+7200)    
    insert into Timezone values(68,NULL,'Namibia Standard Time','(UTC+02:00) Windhoek',NULL,0,+7200)    
    insert into Timezone values(69,NULL,'Arabic Standard Time','(UTC+03:00) Baghdad',NULL,0,+10800)    
    insert into Timezone values(70,NULL,'Turkey Standard Time'  ,'(UTC+03:00) Istanbul',NULL,0,+10800)    
    insert into Timezone values(71,NULL,'Arab Standard Time','(UTC+03:00) Kuwait, Riyadh',NULL,0,+10800)    
    insert into Timezone values(72,NULL,'Belarus Standard Time','(UTC+03:00) Minsk',NULL,0,+10800)    
    insert into Timezone values(73,NULL,'Russian Standard Time','(UTC+03:00) Moscow, St. Petersburg',NULL,0,+10800)    
    insert into Timezone values(74,NULL,'E. Africa Standard Time','(UTC+03:00) Nairobi',NULL,0,+10800)    
    insert into Timezone values(75,NULL,'Iran Standard Time','(UTC+03:30) Tehran',NULL,0,+12600 )    
    insert into Timezone values(76,NULL,'Arabian Standard Time','(UTC+04:00) Abu Dhabi, Muscat',NULL,0,+14400)    
    insert into Timezone values(77,NULL,'Astrakhan Standard Time','(UTC+04:00) Astrakhan, Ulyanovsk',NULL,0,+14400)    
    insert into Timezone values(78,NULL,'Azerbaijan Standard Time','(UTC+04:00) Baku',NULL,0,+14400)    
    insert into Timezone values(79,NULL,'Russia Time Zone 3','(UTC+04:00) Izhevsk, Samara',NULL,0,+14400)    
    insert into Timezone values(80,NULL,'Mauritius Standard Time','(UTC+04:00) Port Louis',NULL,0,+14400)    
    insert into Timezone values(81,NULL,'Saratov Standard Time','(UTC+04:00) Saratov',NULL,0,+14400)    
    insert into Timezone values(82,NULL,'Georgian Standard Time','(UTC+04:00) Tbilisi',NULL,0,+14400)    
    insert into Timezone values(83,NULL,'Volgograd Standard Time','(UTC+04:00) Volgograd',NULL,0,+14400)    
    insert into Timezone values(84,NULL,'Caucasus Standard Time','(UTC+04:00) Yerevan',NULL,0,+14400)    
    insert into Timezone values(85,NULL,'Afghanistan Standard Time','(UTC+04:30) Kabul',NULL,0,+16200)    
    insert into Timezone values(86,NULL,'West Asia Standard Time','(UTC+05:00) Ashgabat, Tashkent',NULL,0,+18000)    
    insert into Timezone values(87,NULL,'Ekaterinburg Standard Time','(UTC+05:00) Ekaterinburg',NULL,0,+18000)    
    insert into Timezone values(88,NULL,'Pakistan Standard Time','(UTC+05:00) Islamabad, Karachi',NULL,0,+18000)    
    insert into Timezone values(89,NULL,'Qyzylorda Standard Time','(UTC+05:00) Qyzylorda',NULL,0,+18000)    
    insert into Timezone values(90,NULL,'India Standard Time','(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi',NULL,0,+19800)    
    insert into Timezone values(91,NULL,'Sri Lanka Standard Time','(UTC+05:30) Sri Jayawardenepur',NULL,0,+19800)    
    insert into Timezone values(92,NULL,'Nepal Standard Time','(UTC+05:45) Kathmandu',NULL,0,+20700)    
    insert into Timezone values(93,NULL,'Central Asia Standard Time','(UTC+06:00) Astana',NULL,0,+21600)    
    insert into Timezone values(94,NULL,'Bangladesh Standard Time','(UTC+06:00) Dhaka',NULL,0,+21600)    
    insert into Timezone values(95,NULL,'Omsk Standard Time','(UTC+06:00) Omsk',NULL,0,+21600)    
    insert into Timezone values(96,NULL,'Myanmar Standard Time','(UTC+06:30) Yangon (Rangoon)',NULL,0,+23400)    
    insert into Timezone values(97,NULL,'SE Asia Standard Time','(UTC+07:00) Bangkok, Hanoi, Jakarta',NULL,0,+25200)    
    insert into Timezone values(98,NULL,'Altai Standard Time','(UTC+07:00) Barnaul, Gorno-Altaysk',NULL,0,+25200)    
    insert into Timezone values(99,NULL,'W. Mongolia Standard Time','(UTC+07:00) Hovd',NULL,0,+25200)    
    insert into Timezone values(100,NULL,'North Asia Standard Time','(UTC+07:00) Krasnoyarsk',NULL,0,+25200)    
    insert into Timezone values(101,NULL,'N. Central Asia Standard Time','(UTC+07:00) Novosibirsk',NULL,0,+25200)    
    insert into Timezone values(102,NULL,'Tomsk Standard Time','(UTC+07:00) Tomsk',NULL,0,+25200)    
    insert into Timezone values(103,NULL,'China Standard Time','(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi',NULL,0,+28800)    
    insert into Timezone values(104,NULL,'North Asia East Standard Time','(UTC+08:00) Irkutsk',NULL,0,+28800)    
    insert into Timezone values(105,NULL,'Singapore Standard Time','(UTC+08:00) Kuala Lumpur, Singapore',NULL,0,+28800  )    
    insert into Timezone values(106,NULL,'W. Australia Standard Time','(UTC+08:00) Perth',NULL,0,+28800)    
    insert into Timezone values(107,NULL,'Taipei Standard Time','(UTC+08:00) Taipei',NULL,0,+28800)    
    insert into Timezone values(108,NULL,'Ulaanbaatar Standard Time','(UTC+08:00) Ulaanbaatar',NULL,0,+28800)    
    insert into Timezone values(109,NULL,'Aus Central W. Standard Time','(UTC+08:45) Eucla',NULL,0,+31500)    
    insert into Timezone values(110,NULL,'Transbaikal Standard Time','(UTC+09:00) Chita',NULL,0,+32400  )    
    insert into Timezone values(111,NULL,'Tokyo Standard Time','(UTC+09:00) Osaka, Sapporo, Tokyo',NULL,0,32400)    
    insert into Timezone values(112,NULL,'North Korea Standard Time','(UTC+09:00) Pyongyang',NULL,0,+32400)    
    insert into Timezone values(113,NULL,'Korea Standard Time','(UTC+09:00) Seoul',NULL,0,+32400)    
    insert into Timezone values(114,NULL,'Yakutsk Standard Time','(UTC+09:00) Yakutsk',NULL,0,+32400)    
    insert into Timezone values(115,NULL,'Cen. Australia Standard Time','(UTC+09:30) Adelaide',NULL,0,+34200)    
    insert into Timezone values(116,NULL,'AUS Central Standard Time','(UTC+09:30) Darwin',NULL,0,+34200)    
    insert into Timezone values(117,NULL,'E. Australia Standard Time','(UTC+10:00) Brisbane',NULL,0,+36000)    
    insert into Timezone values(118,NULL,'AUS Eastern Standard Time','(UTC+10:00) Canberra, Melbourne, Sydney',NULL,0,+36000)    
    insert into Timezone values(119,NULL,'West Pacific Standard Time','(UTC+10:00) Guam, Port Moresby',NULL,0,+36000)    
    insert into Timezone values(120,NULL,'Tasmania Standard Time','(UTC+10:00) Hobart',NULL,0,+36000)    
    insert into Timezone values(121,NULL,'Vladivostok Standard Time','(UTC+10:00) Vladivostok',NULL,0,+36000)    
    insert into Timezone values(122,NULL,'Lord Howe Standard Time','(UTC+10:30) Lord Howe Island',NULL,0,+37800)    
    insert into Timezone values(123,NULL,'Bougainville Standard Time','(UTC+11:00) Bougainville Island',NULL,0,+39600)    
    insert into Timezone values(124,NULL,'Russia Time Zone 10','(UTC+11:00) Chokurdakh',NULL,0,+39600)    
    insert into Timezone values(125,NULL,'Magadan Standard Time','(UTC+11:00) Magadan',NULL,0,+39600)    
    insert into Timezone values(126,NULL,'Norfolk Standard Time','(UTC+11:00) Norfolk Island',NULL,0,+39600)    
    insert into Timezone values(127,NULL,'Sakhalin Standard Time','(UTC+11:00) Sakhalin',NULL,0,+39600)    
    insert into Timezone values(128,NULL,'Central Pacific Standard Time','(UTC+11:00) Solomon Is., New Caledonia',NULL,0,+39600)    
    insert into Timezone values(129,NULL,'Russia Time Zone 11','(UTC+12:00) Anadyr, Petropavlovsk-Kamchatsky',NULL,0,+43200)    
    insert into Timezone values(130,NULL,'New Zealand Standard Time','(UTC+12:00) Auckland, Wellington',NULL,0,+43200)    
    insert into Timezone values(131,NULL,'UTC+12','(UTC+12:00) Coordinated Universal Time+12',NULL,0,+43200)    
    insert into Timezone values(132,NULL,'Fiji Standard Time','(UTC+12:00) Fiji',NULL,0,+43200)    
    insert into Timezone values(133,NULL,'Kamchatka Standard Time','(UTC+12:00) Petropavlovsk-Kamchatsky - Old',NULL,0,+43200)    
    insert into Timezone values(134,NULL,'Chatham Islands Standard Time','(UTC+12:45) Chatham Islands',NULL,0,+45900)    
    insert into Timezone values(135,NULL,'UTC+13','(UTC+13:00) Coordinated Universal Time+13',NULL,0,+46800)    
    insert into Timezone values(136,NULL,'Tonga Standard Time','(UTC+13:00) Nuku alofa',NULL,0,+46800)    
    insert into Timezone values(137,NULL,'Samoa Standard Time','(UTC+13:00) Samoa',NULL,0,+46800)    
    insert into Timezone values(138,NULL,'Line Islands Standard Time','(UTC+14:00) Kiritimati Island',NULL,0,+50400) 
 

Step 3 - Create a function for Convert UTC timezone to any given timezone
Pass the UTC DateTime and timezone in the function,
    CREATE FUNCTION [dbo].[ConvertUTCtoLocal]    
    (    
       -- Add the parameters for the function here    
         @utcDateTime DATETIME,    
         @strTimeZoneName varchar(100)    
    )    
    RETURNS Datetime    
    AS    
    BEGIN    
    -- Declare the return variable here    
    --the original date    
    DECLARE @m_createddate as Datetime  ,@BaseUtcOffsetSec AS INT    
       SELECT @BaseUtcOffsetSec =BaseUtcOffsetSec FROM  Timezone WHERE StandardName=@strTimeZoneName    
    -- Return the result of the function    
     select   @m_createddate=DATEADD(SECOND, @BaseUtcOffsetSec,@utcDateTime)    
    RETURN @m_createddate    
    END    


Step 4
Result using User Defined Function of SQL,
    SELECT [dbo].[ConvertUTCtoLocal] (GETUTCDATE(),'Central Standard Time')    

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