European Windows 2019 Hosting BLOG

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

SQL Server Hosting - HostForLIFE :: SQL Server Express - Database Backup Scheduler

clock July 26, 2021 08:09 by author Peter

In this article, we will learn how to create a database backup scheduler in the SQL Express version as it has no built-in auto backup tool like SQL Server. With the help of Task Scheduler (Windows OS) and batch file, we will create a schedular to take the database backup from the SQL Express version in the specified folder.

Requirement

Batch File
Stored Procedure (Database Backup) which is not available in SQL Express version
Configuration on Windows Task Scheduler

Let's get started,

Batch File

Create a batch file as below,

Open notepad and paste the below code and change the parameters as per your configuration and save this file as a .bat extension.
sqlcmd -S .\SQLEXPRESS_Instance_Name -E -Q "EXEC sp_BackupDatabases @backupLocation='D:\Backup\', @databaseName='DatabaseName', @backupType='F'"

ActionScript

In the above statement, sp_BackupDatabases is a stored procedure name that we will create in the next step.

Stored Procedure (Database Backup)

In SQL Express we have to add the below-stored procedure in the default Master database as SQL Express does not provide built-in auto back feature.

We will create the below-stored procedure in the Master database which is a default database provided by SQL Express.

Note
The below-stored procedure is written by Microsoft.

Copied from https://raw.githubusercontent.com/microsoft/mssql-support/master/sample-scripts/backup_restore/SQL_Express_Backups.sql
USE [master]
GO
/****** Object:  StoredProcedure [dbo].[sp_BackupDatabases]    Script Date: 17/07/2021 11:35:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Microsoft
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================
ALTER PROCEDURE [dbo].[sp_BackupDatabases]
        @databaseName sysname = null,
        @backupType CHAR(1),
        @backupLocation nvarchar(200)
AS
   SET NOCOUNT ON;
        DECLARE @DBs TABLE
        (
              ID int IDENTITY PRIMARY KEY,
              DBNAME nvarchar(500)
        )
         -- Pick out only databases which are online in case ALL databases are chosen to be backed up
         -- If specific database is chosen to be backed up only pick that out from @DBs
        INSERT INTO @DBs (DBNAME)
        SELECT Name FROM master.sys.databases
        where state=0
        AND name= ISNULL(@DatabaseName ,name)
        ORDER BY Name
        -- Filter out databases which do not need to backed up
        IF @backupType='F'
              BEGIN
              DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
              END
        ELSE IF @backupType='D'
              BEGIN
              DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
              END
        ELSE IF @backupType='L'
              BEGIN
              DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
              END
        ELSE
              BEGIN
              RETURN
              END
        -- Declare variables
        DECLARE @BackupName varchar(100)
        DECLARE @BackupFile varchar(100)
        DECLARE @DBNAME varchar(300)
        DECLARE @sqlCommand NVARCHAR(1000)
        DECLARE @dateTime NVARCHAR(20)
        DECLARE @Loop int
        -- Loop through the databases one by one
        SELECT @Loop = min(ID) FROM @DBs
  WHILE @Loop IS NOT NULL
  BEGIN
-- Database Names have to be in [dbname] format since some have - or _ in their name
  SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'
-- Set the current date and time n yyyyhhmmss format
  SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' +  REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- Create backup filename in path\filename.extension format for full,diff and log backups
  IF @backupType = 'F'
        SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
  ELSE IF @backupType = 'D'
        SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
  ELSE IF @backupType = 'L'
        SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'
-- Provide the backup a name for storing in the media
  IF @backupType = 'F'
        SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
  IF @backupType = 'D'
        SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
  IF @backupType = 'L'
        SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime
-- Generate the dynamic SQL command to be executed
   IF @backupType = 'F'
              BEGIN
           SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
              END
   IF @backupType = 'D'
              BEGIN
           SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
              END
   IF @backupType = 'L'
              BEGIN
           SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+  ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
              END
-- Execute the generated SQL command
   EXEC(@sqlCommand)
-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop
END


Windows Task Scheduler Configuration

Now we will create a windows scheduler to run the batch file to run the above-stored procedure to create an automated backup which is a final step.

Open Task Scheduler as below (type task scheduler from the search bar of windows 10 and press enter).

Create a new task as below,


We will give the name to our scheduler task and select the appropriate option as below. We need to run this scheduler all time so we select this selected option shown below screen.

Now we will set our scheduler - when to run this task using the Trigger tab as below screen and then click on the new button.

Now will create a new trigger to tell the system when to run this task as below. Please configure it as per your requirement.


Once the trigger is set we will now configure the action tab and then click the new button to setup our above-created batch file. We will call our batch file with the help of the action tab as below,

Click on the new button to set the path of our batch file as below,

Once we browse and select the created batch file then click the ok button. And then click on the condition tab to configure it. We will keep default settings as below,


And now final configuration, click on the settings tab as below. Again we will keep default settings as below,

Click the ok button will create your task and will run this task as per your configuration. Note: It will ask to enter windows credentials which have admin rights if you do not have enough rights to create such a task.

Once all set, the scheduler will run the task to call the batch file and that batch file will call the stored procedure to get the backup of mentioned database in the batch file.

Note

Please make sure that the information you mention in the batch is correct.
Happy Coding!!

 

HostForLIFEASP.NET SQL Server 2019 Hosting



 



SQL Server Hosting - HostForLIFE :: Get All Columns in a Table Schema Information In One Click

clock July 23, 2021 07:46 by author Peter

In this article, we will learn how to get all the column information of a table with one click, including Column Name, DataType, Data Length, Column Description, etc. I found this technique very useful when I had to share the table column information along with some sample data into an Excel sheet with other clients.

Sample Script

In this script, we need to pass only the table name and schema name.

set @TableSchema ='dbo' --Schema name table 'Item' set @TableName= 'Item' -- Name of table.
declare @TableSchema varchar(50)
declare @TableName varchar(50)

set @TableSchema ='dbo' --Edit as per your table schema
set @TableName= 'Item' --Edit as per your table name

select @TableSchema +'.' +@TableName TableName

SELECT ORDINAL_POSITION AS [SNo],

COLUMN_NAME AS [Column Name],

DATA_TYPE AS [Data Type],

CASE
    WHEN DATA_TYPE ='decimal'  THEN  '(' + convert(varchar(20),NUMERIC_PRECISION) + ','  + convert(varchar(20),NUMERIC_SCALE) + ')'
    WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN ''
    WHEN CHARACTER_MAXIMUM_LENGTH ='-1' then 'MAX'
    ELSE CONVERT(varchar(50), CHARACTER_MAXIMUM_LENGTH)
End  AS [Length],

CASE WHEN COL.IS_NULLABLE = 'No' THEN 'Y' ELSE 'Yes' End [Is Mandatory],

ISNULL(prop.value,'') [Description]

FROM INFORMATION_SCHEMA.TABLES AS tbl
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS col
ON col.TABLE_NAME = tbl.TABLE_NAME
AND tbl.TABLE_SCHEMA=col.TABLE_SCHEMA
AND tbl.table_schema=@TableSchema
AND tbl.TABLE_NAME = @TableName
INNER JOIN sys.columns AS sc
ON sc.object_id = object_id(tbl.table_schema + '.' + tbl.table_name)
AND sc.NAME = col.COLUMN_NAME
AND tbl.TABLE_SCHEMA=@TableSchema
AND tbl.TABLE_NAME = @TableName
LEFT JOIN sys.extended_properties AS prop
ON prop.major_id = sc.object_id
AND prop.minor_id = sc.column_id
AND prop.NAME = 'MS_Description'
WHERE tbl.table_schema=@TableSchema and tbl.TABLE_NAME = @TableName
order by ORDINAL_POSITION


When you execute this script, it shows the column information like the following screenshot,



How to Prepare Excel Sheet With Sample Data

Step 1
Copy this result data with Headers information. Right click on the first cell -> click on the menu [Copy with Headers] and paste it into your excel sheet.

Step 2

Now, we have to paste few sample data into this excel sheet. For this, I will execute the following script.
Select top 2 * From dbo.Item  --

Step 3

Now copy the result and data without header columns.

Step 4

Now paste this copied data into another excel sheet.

Step 5
Now again copy this data from the excel sheet where you have pasted it.

Step 6
Now transpose this data into the first sheet where you have pasted column information.

Note
In Excel paste options, you can find this transpose option which will paste your records in column format.

Finally, it will look like the following screenshot,

 

HostForLIFEASP.NET SQL Server 2019 Hosting



Europe SQL Hosting - HostForLIFEASP.NET :: Triggers in SQL Server

clock July 13, 2021 08:32 by author Peter

A SQL trigger is a database object which fires when an event occurs in a database. We can execute a SQL query that will "do something" in a database when a change occurs on a database table such as a record is inserted or updated or deleted. For example, a trigger can be set on a record insert in a database table. For example, if you want to increase the count of blogs in the Reports table when a new record is inserted in the Blogs table, we can create a trigger on the Blogs' table on INSERT and update the Reports table by increasing blog count to 1.

Types of Triggers
There are two types of triggers:
    DDL Trigger
    DML Trigger

DDL Triggers
The DDL triggers are fired in response to DDL (Data Definition Language) command events that start with Create, Alter and Drop, such as Create_table, Create_view, drop_table, Drop_view and Alter_table.

Code of a DDL Trigger

create trigger saftey
on database
for
create_table,alter_table,drop_table
as
print'you can not create ,drop and alter table in this database'
rollback;

When we create, alter or drop any table in a database then the following message appears:

 

DML Triggers
The DML triggers are fired in response to DML (Data Manipulation Language) command events that start with Insert, Update, and Delete. Like insert_table, Update_view and Delete_table.

create trigger deep
on emp
for
insert,update,delete
as
print'you can not insert,update and delete this table i'
rollback;

When we insert, update or delete in a table in a database then the following message appears,

There are two types of DML triggers
 
AFTER Triggers
AFTER triggers are executed after the action of an INSERT, UPDATE, or DELETE statement.

create trigger insertt
on emp
after insert
as
begin
insert into empstatus values('active')
end


INSTEAD Of Triggers

It will tell the database engine to execute the trigger instead of executing the statement. For example an insert trigger executes when an event occurs instead of the statement that would insert the values in the table .
CREATE TRIGGER instoftr
ON v11
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO emp
SELECT I.id, I.names
FROM INSERTED I

INSERT INTO emp1values
SELECT I.id1, I.name1
FROM INSERTED I
END

When we insert data into a view by the following query then it inserts values in both tables :
insert into v11 values(1,'d','dd')

You can see both tables by the folowing query:
select * from emp
select * from emp1values


In this article, I described triggers in SQL Server. I hope this article has helped you in understanding this topic. Please share it. If you know more about this, your feedback and constructive contributions are welcome.

Continue learning more, Trigger in SQL

 

 

 



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



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