European Windows 2012 Hosting BLOG

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

European SQL Hosting :: Performance Between CLR vs T-SQL

clock March 6, 2019 08:17 by author Scott

I am pretty sure that all of us read or even participated in quite a few heated discussions about Common Language Runtime (CLR) code in Microsoft SQL Server. Some people state that CLR code works faster than T-SQL, others oppose them. Although, as with the other SQL Server technologies, there is no simple answer to that question. Both technologies are different in nature and should be used for the different tasks. T-SQL is the interpreted language, which is optimized for set-based logic and data access. CLR, on the other hand, produces compiled code that works the best for imperative procedural-style code.

Even with imperative code, we need to decide if we want to implement it in CLR or as the client-side code, perhaps running on the application servers. CLR works within SQL Server process. While, on one hand, it eliminates network traffic and can provide us the best performance due to the “closeness” to the data, CLR adds the load to the SQL Server. It is usually easier and cheaper to scale out application servers rather than upgrading SQL Server box.

There are some cases when we must use CLR code though. For example, let’s think about the queries that performing RegEx evaluations as part of the where clause. It would be inefficient to move such evaluations to the client code and there is no regular expressions support in SQL Server. So CLR is the only choice we have. Although, in the other cases, when procedural-style logic can be moved to the application servers, we should consider such option. Especially when application servers are residing closely to SQL Server and network latency and throughput are not an issue.

Today we will compare performance of the few different areas of CLR and T-SQL. I am not trying to answer the question – “what technology is better”. As usual it fits into “It depends” category. What I want to do is looking how technologies behave in the similar tasks when they can be interchanged.

Before we begin, let’s create the table and populate it with some data.


As the first step, let’s compare the user-defined functions invocation cost. We will use the simple function that accepts the integer value as the parameter and returns 1 in case if that value is even. We can see CLR C# implementation below.

As we can see, there are the attributes specified for each function. Those attributes describes different aspects of UDF behavior and can help Query Optimizer to generate more efficient execution plans. I would recommend specifying them explicitly rather than relying on default values.

One of the attributes – DataAccess – indicates if function performs any data access. When this is the case, SQL Server calls the function in the different context that will allow access to the data. Setting up such context introduces additional overhead during the functional call, which we will see in a few minutes.

T-SQL implementation of those functions would look like that:


Let’s measure average execution time for the statements shown below. Obviously, different hardware leads to the different execution time although trends would be the same.

Each statement performs clustered index scan of dbo.Numbers table and checks if Num column is even for every row from the table. For CLR and T-SQL scalar user-defined functions, that introduces the actual function call. Inline multi-statement function, on the other hand, performed the calculation inline without function call overhead.

As we can see, CLR UDF without data access context performs about four times faster comparing to T-SQL scalar function. Even if establishing data-access context introduces additional overhead and increases execution time, it is still faster than T-SQL scalar UDF implementation.

The key point here though is than in such particular example the best performance could be achieved if we stop using the functions at all rather than converting T-SQL implementation to CLR UDF. Even with CLR UDF, the overhead of the function call is much higher than inline calculations.

Unfortunately, this is not always the case. While we should always think about code refactoring as the option, there are the cases when CLR implementation can outperform inline calculations even with all overhead it introduced. We are talking about mathematical calculations, string manipulations, XML parsing and serialization – to name just a few. Let’s test the performance of the functions that calculate the distance between two points defined by latitude and longitude.

 



We can see that CLR UDF runs almost two times faster comparing to inline table-valued functions and more than five times faster comparing to T-SQL scalar UDF. Even with all calling overhead involved.

Now let’s look at the data access performance. The first test compares performance of the separate DML statements from T-SQL and CLR stored procedures. In that test we will create the procedures that calculate the number of the rows in dbo.Numbers table for specific Num interval provided as the parameters. We can see the implementation below

Table below shows the average execution time for stored procedure with the parameters that lead to 50,000 individual SELECT statements. As we can see, data access from CLR code is much less efficient and works about five times slower than data access from T-SQL.

Now let’s compare performance of the row-by-row processing using T-SQL cursor and .Net SqlDataReader class.

As we can see, SqlDataReader implementation is faster.

Finally, let’s look at the performance of CLR aggregates. We will use standard implementation of the aggregate that concatenates the values into comma-separated string.


As with user-defined functions, it is extremely important to set the attributes that tell Query Optimizer about CLR Aggregate behavior and implementation. This would help to generate more efficient execution plans and prevent incorrect results due to optimization. It is also important to specify MaxByteSize attribute that defines the maximum size of the aggregate output. In our case, we set it to -1 which means that aggregate could hold up to 2GB of data.

Speaking of T-SQL implementation, let’s look at the approach that uses SQL variable to hold intermediate results. That approach implements imperative row-by-row processing under the hood.

As another option let’s use FOR XML PATH technique. It is worth to mention that this technique could introduce different results by replacing XML special characters with character entities. For example, if our values contain < character, it would be replaced with &lt; string.

Our test code would look like that:


When we compare the performance on the different row set sizes, we would see results below

As we can see, CLR aggregate has slightly higher startup cost comparing to T-SQL variable approach although it quickly disappears on the larger rowsets. Performance of both: CLR aggregate and FOR XML PATH methods linearly depend on the number of the rows to aggregate while performance of SQL Variable approach degrade exponentially. SQL Server needs to initiate the new instance of the string every time it concatenates the new value and it does not work efficiently especially when it needs to be populated with the large values.

The key point I would like to make with that example is that we always need to look at the options to replace imperative code with declarative set-based logic. While CLR usually outperforms procedural-style T-SQL code, set-based logic could outperform both of them.

While there are some cases when choice between technologies is obvious, there are the cases when it is not clear. Let us think about scalar UDF that needs to perform some data access. Lower invocation cost of CLR function can be mitigated by higher data access cost from there. Similarly, inline mathematical calculations in T-SQL could be slower than in CLR even with all invocation overhead involved. In those cases, we must test different approaches and find the best one which works in that particular case.



SQL Server 2016 Hosting - HostForLIFE.eu :: Difference Between TRUNCATE, DELETE, And DROP In SQL Server

clock February 27, 2019 11:25 by author Peter

The difference between TRUNCATE, DELETE, and DROP is one of the most common interview question. Here are some of the common differences between them.

TRUNCATE

TRUNCATE SQL query removes all rows from a table, without logging the individual row deletions.

The following example removes all data from the Customers table.

TRUNCATE TABLE Customers;  
TRUNCATE is a DDL command
TRUNCATE is executed using a table lock and whole table is locked for remove all records.
We cannot use WHERE clause with TRUNCATE.
TRUNCATE removes all rows from a table.
Minimal logging in transaction log, so it is performance wise faster.
TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
Identify column is reset to its seed value if table contains any identity column.
To use Truncate on a table you need at least ALTER permission on the table.
Truncate uses the less transaction space than Delete statement.
Truncate cannot be used with indexed views.
TRUNCATE is faster than DELETE.

DELETE
To execute a DELETE queue, delete permissions are required on the target table. If you need to use a WHERE clause in a DELETE, select permissions are required as well.

The following query deletes all rows from the Customers table. 
DELETE FROM Customers; 
GO


The following SQL query deletes all rows from the Customers table where OrderID is greater than 1000.

DELETE FROM Customers WHERE OrderId > 1000; 
GO 


DELETE is a DML command.
DELETE is executed using a row lock, each row in the table is locked for deletion.
We can use where clause with DELETE to filter & delete specific records.
The DELETE command is used to remove rows from a table based on WHERE condition.
It maintain the log, so it slower than TRUNCATE.
The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row.
Identity of column keep DELETE retain the identity.
To use Delete you need DELETE permission on the table.
Delete uses the more transaction space than Truncate statement.
Delete can be used with indexed views.

DROP
DROP table query removes one or more table definitions and all data, indexes, triggers, constraints, and permission specifications for those tables. DROP command requires ALTER permission on the schema to which the table belongs, CONTROL permission on the table, or membership in the db_ddladmin fixed database role.

The following SQL query drops the Customers table and its data and indexes from the current database.
DROP TABLE Customers ; 

The DROP command removes a table from the database.
All the tables' rows, indexes and privileges will also be removed.
No DML triggers will be fired.
The operation cannot be rolled back.
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



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

clock February 20, 2019 10:22 by author Peter

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

I can explain the functionality with two scenarios.

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

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

Test results from SSMS can be seen below.

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

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

Test results from SSMS are shown below.

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

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: AES Encryption/Decryption With Angular 7

clock February 15, 2019 10:15 by author Peter

Most of the time, a developer requires encryption and decryption for encoding a message or information in such a way that only authorized person can retrieve that information.
In this article, I will discuss the implementation of AES encryption and decryption with Angular 7 while developing an application.

So, the first question that comes in our mind is "What is AES?".
AES stands for "Advanced Encryption Standard".
It is a tool that is used to encrypt and decrypt the simple text using AES encryption algorithm.
This algorithm was developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.
AES was designed to be efficient in both, hardware and software, and supports a block length of 128 bits and key lengths of 128, 192, and 256 bits.

When to use AES Encryption

When you want to encrypt a confidential text into a decryptable format, for example - when you need to send some sensitive data in an e-mail.
The decryption of the encrypted text is possible only if you know the right password.

Now, try to implement the AES encryption and decryption in Angular 7. It's very easy to implement in Angular 7 with the help of crypto-js.

First, we create a new project with the following command.
ng new EncryptionDescryptionSample 

After that, install crypto.js file, by the following command.
npm install crypto-js --save 

For better UI, we also install bootstrap by the following command.
npm install bootstrap --save 

After running the above command, check the package.json file if it is installed or not. Your file should look like this.
AES Encryption/Decryption with Angular 7

Now, go to "app.component.html" file and replace the existing code with the below code.
<h1 class="text-center">Encrypt-Decrypt with AES</h1> 
 
<br> 
<div> 
  <div class="row"> 
    <div class="col-sm-6"> 
      <button type="button" class="btn btn-primary btn-lg btn-block"> 
        Encryption 
      </button> 
      <br> 
      <div class="form-group"> 
        <label for="txtTextToConvert">Plain Text</label> 
        <input type="text" class="form-control" placeholder="Enter text you want to encrypt" [(ngModel)]="plainText"> 
      </div> 
 
      <div class="form-group"> 
        <label for="txtPassword">Password</label> 
        <input type="password" class="form-control" placeholder="Enter encryption password" [(ngModel)]="encPassword"> 
      </div> 
      <textarea class="form-control" readonly rows="3">{{conversionEncryptOutput}}</textarea> 
      <br> 
      <button type="button" class="btn btn-success float-right" (click)="convertText('encrypt')">Encrypt</button> 
    </div> 
    <div class="col-sm-6"> 
      <button type="button" class="btn btn-dark btn-lg btn-block"> 
        Decryption 
      </button> 
      <br> 
      <div class="form-group"> 
        <label for="txtTextToConvert">Encrypted Text</label> 
        <input type="text" class="form-control" placeholder="Enter text you want to decrypt" [(ngModel)]="encryptText"> 
      </div> 
 
      <div class="form-group"> 
        <label for="txtPassword">Password</label> 
        <input type="password" class="form-control" placeholder="Enter decryption password" [(ngModel)]="decPassword"> 
      </div> 
      <textarea class="form-control" readonly rows="3">{{conversionDecryptOutput}}</textarea> 
      <br> 
      <button type="button" class="btn btn-success float-right" (click)="convertText('decrypt')">Decrypt</button> 
    </div> 
  </div> 
</div> 


Now, visit "app.component.ts" file and write the below code,
import { Component } from '@angular/core'; 
import * as CryptoJS from 'crypto-js'; 
 
@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
  title = 'EncryptionDecryptionSample'; 
   
  plainText:string; 
  encryptText: string; 
  encPassword: string; 
  decPassword:string; 
  conversionEncryptOutput: string; 
  conversionDecryptOutput:string; 
   
  constructor() { 
  } 
  //method is used to encrypt and decrypt the text 
  convertText(conversion:string) { 
      if (conversion=="encrypt") { 
        this.conversionEncryptOutput = CryptoJS.AES.encrypt(this.plainText.trim(), this.encPassword.trim()).toString(); 
      } 
      else { 
        this.conversionDecryptOutput = CryptoJS.AES.decrypt(this.encryptText.trim(), this.decPassword.trim()).toString(CryptoJS.enc.Utf8); 
      
    } 
  } 


In the above code, we used the Encrypt method of AES and passed our plain text with a password to encrypt the string. Similarly, we used the Decrypt method of AES and passed our encrypted text with a password to decrypt the string. Be sure that both times, your password is the same. For using both of these methods, you need to import "CryptoJS" from crypto-js.
import * as CryptoJS from 'crypto-js'; 

Now, let us run the project by using the following command.
ng serve --o 

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server 2016 Hosting - HostForLIFE.eu :: Brief Introduction To Indexes In SQL Server

clock February 12, 2019 10:42 by author Peter

If you want to find a record in a table without having an index, the system will scan the whole table to get that record. Well, this is a very costly operation in terms of time. For example, if your table has 10 million records, it will scan all these records to find the value. To overcome this problem, indexes are used. Indexes use the B-TREE search algorithm to search a record in a table, which is way faster than the table scan.

Types of Index
Below are the frequently used types of Indexes.

  • Clustered Index
    A clustered index is an index that defines the physical order of records to be stored in a table. Therefore, the table can have only one clustered index. 
  • Non-Clustered Index
    A non-clustered index is similar to an index in a book. The data is stored in one place and the index is stored in another place. Here, the index has pointers to the storage location of the data. Therefore, a table can have more than one Non-clustered index. 
The syntax for creating an index.
CREATE INDEX <Index Name>  
ON <Table Name> (<Column Name>);  
  
/*Example of creating index on Lastname column of Persons table*/  
  
CREATE INDEX idx_lastname  
ON Persons (LastName); 

Benefits of indexing foreign key columns

There are two primary benefits of using the Index on foreign key.
  1. Makes delete operation of parent table faster
    When you delete a row from a parent table, the SQL Server checks if there are any rows which reference the row being deleted in the child table. To find the rows efficiently, an index on the foreign key column is extremely useful.
  2. Making joins faster
    Using Index, SQL Server can more effectively find the rows to join to when the child and parent tables are joined.

Can we have multiple indexes on the same column?

  • As you can have only one clustered index per table, you cannot have multiple clustered indexes on the same column; however, you can have multiple non-clustered indices on the same column.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2017 Hosting :: How to Know that Your SQL Server Eat too Much Memory?

clock January 29, 2019 08:14 by author Scott

Sounds impossible, right? The saying goes that you can never be too rich or too thin or have too much memory.

However, there is one good indication that your SQL Server is probably overprovisioned, and to explain it, I need to cover 3 metrics.

1. Max Server Memory is set at the instance level: right-click on your SQL Server name in SSMS, click Properties, Memory, and it’s “Maximum server memory.” This is how much memory you’re willing to let the engine use. (The rocket surgeons in the audience are desperate for the chance to raise their hands to point out different things that are or aren’t included in max memory – hold that thought. That’s a different blog post.)

2. Target Server Memory is how much memory the engine is willing to use. You can track this with the Perfmon counter SQLServer:Memory Manager – Target Server Memory (KB):

SELECT *
FROM sys.dm_os_performance_counters
WHERE counter_name LIKE '%Target Server%';

Generally, when you start up SQL Server, the target is set at your max. However, SQL Server doesn’t allocate all of that memory by default. (Again, the experts wanna raise hands and prove how much they know – zip it.)

3. Total Server Memory is roughly how much the engine is actually using. (Neckbeards – seriously – zip it until the end of the post. I’m not playing.) After startup, SQL Server will gradually use more and more memory as your queries require it. Scan a big index? SQL Server will start caching as much of that index as it can in memory. You’ll see this number increase over time until – generally speaking – it matches target server memory.

SELECT *
FROM sys.dm_os_performance_counters
WHERE counter_name LIKE '%Total Server%';

What if Total Server Memory doesn’t go up?

Say you have a SQL Server with:

  • 64GB memory
  • Max memory set to 60GB
  • 1GB of total database size (just to pick an extreme example)

Infrequent query workloads (we don’t have hundreds of users trying to sort the database’s biggest table simultaneously, or do cartesian joins)

SQL Server might just not ever need the memory.

And in a situation like this, after a restart, you’ll see Total Server Memory go up to 2-3GB and call it a day. It never rises up to 10GB, let alone 60GB. That means this SQL Server just has more memory than it needs.

Here’s an example of a server that was restarted several days ago, and still hasn’t used 4GB of its 85GB max memory setting. Here, I’m not showing max memory – just the OS in the VM, and target and total:



In most cases, it’s not quite that black-and-white, but you can still use the speed at which Total Server Memory rises after a reboot to get a rough indication of how badly (and quickly) SQL Server needs that memory. If it goes up to Target Server Memory within a couple of hours, yep, you want that memory bad. But if it takes days? Maybe memory isn’t this server’s biggest challenge.

Exceptions obviously apply – for example, you might have an accounting server that only sees its busiest activity during close of business periods. Its memory needs might be very strong then, but not such a big deal the rest of the month.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Scheduling Things To Run In SQL Server?

clock January 23, 2019 10:21 by author Peter

A key part of the SQL Server Agent is the ability to schedule jobs. While you can create one schedule for each agent job, frequently with applications like Reporting Services, users use Shared Schedules across multiple jobs. For instance, you can set a schedule to run at 8 am on week days or run every 2 hours or pick from a predefined list of schedules that already exist in the MSDB database. These are very convenient. However, if you choose to use these be sure you are keeping track of what is running for each of these shared schedules. You should not have everything running at once.

This is an example of a job schedule in a Management Studio SQL Server Agent Job. You can create a new one or pick from a list of already made schedules.

There’s nothing inherently wrong with using shared schedules—some very small operations can all run at the same time, however when you start to use them for larger operations you can really impact the overall performance of your server.

Many times, I have seen high CPU or locks as well as many other performance issues due to the system being overloaded with jobs running on shared schedules or all at the same time (midnight is a frequently common choice). Not every report to should run at 8 am and every data load run every 2 hours. If you not using shared schedules or added a separate schedule per job it is also important to make sure you are not running up against other things running. If you are using applications like SSRS, then you need to pay attention to when the report subscription refreshes are happening. Don’t overload your system by having everything run at once. Job and subscription schedules need to be analyzed and evaluated just like everything else you care for in your database.

To keep this from happening consult your agent jobs to see what other jobs are running before scheduling additional ones. You can easily get a glimpse in Job activity monitor to see what’s running and when it will run next.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



AngularJS Hosting - HostForLIFE.eu :: How to Create Cascading Dropdown in AngularJS?

clock January 16, 2019 11:50 by author Peter

In this post, I will make a Cascading Dropdown in AngularJS. Add 2 Class 1 for Countries and other for state. Write the following code:
public class Country 

    public int CountryId { get; set; } 
    public string CountryName { get; set; } 

public class State 

    public int StateId { get; set; } 
    public string StateName { get; set; } 
    public int CountryId { get; set; } 

Create a ActionResult Name it as Index [Add a View].

Add the script

<script src="~/Scripts/angular.min.js"></script> 

Create a js Name it in my case its CascadingDropdown.

var app = angular.module('myApp', []); 
app.controller('myController', function ($scope, $http) { 
    getcountries(); 
    function getcountries() { 
     
        $http({ 
            method: 'Get', 
            url: '/Home/Countries' 
 
        }).success(function (data, status, header, config) { 
 
            $scope.countries = data; 
        }).error(function (data, status, header, config) { 
            $scope.message = "Error"; 
        }); 
    } 
 
    $scope.GetStates = function ()  
    { 
        var countryIdselected = $scope.countrymodel; 
        if (countryIdselected) { 
            $http({ 
                method: 'Post', 
                url: '/Home/States', 
                data: JSON.stringify({ countryId: countryIdselected }) 
            }).success(function (data, status, header, config) { 
                $scope.states = data; 
            }).error(function (data, status, header, config) { 
                $scope.message = "Error"; 
            }) 
        } 
        else { 
            $scope.states = null; 
        } 
    } 
}); 
 
 
//Calls for Country DropDown 
 public ActionResult Countries() 
        { 
            List<Country> cobj = new List<Country>(); 
            cobj.Add(new Country { CountryId = 1, CountryName = "India" }); 
            cobj.Add(new Country { CountryId = 2, CountryName = "Srilanka" }); 
            cobj.Add(new Country { CountryId = 3, CountryName = "USA" }); 
 
            return Json(cobj, JsonRequestBehavior.AllowGet); 
        } 
 
//Calls for State DropDown with CountryID as Parameter 
 
        public ActionResult States(int countryId) 
        { 
   List<State> sobj = new List<State>(); 
   sobj.Add(new State { StateId = 1, StateName = "Karnataka", CountryId = 1 }); 
   sobj.Add(new State { StateId = 2, StateName = "Kerala", CountryId = 1 }); 
   sobj.Add(new State { StateId = 3, StateName = "TamilNadu", CountryId = 1 }); 
   sobj.Add(new State { StateId = 1, StateName = "Newyork", CountryId = 3 }); 
   sobj.Add(new State { StateId = 1, StateName = "Colombo", CountryId = 2 }); 
 
//Filter based on CountryID 
            var result = sobj.Where(x => x.CountryId == countryId).Select(x => new { x.StateId, x.StateName }); 
 
            return Json(result); 
        } 
 
//IndexView 
//  Add the script file <script src="~/Scripts/CascadingDropdown.js"></script> 
<div ng-app="myApp"> 
       
            <form name="mainForm"  ng-controller="myController"> 
 
                <select ng-model="countrymodel" ng-options=" c.CountryId as c.CountryName for c in countries" ng-change="GetStates()"> 
                    <option value="">-- Select Country --</option> 
                </select> 
                <select ng-model="statemodel" ng-options="s.StateId as s.StateName for s in states "> 
                    <option value="">-- Select State --</option> 
                </select> 
            </form> 
</div>  


I hope it works for you!

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2016 Hosting - HostForLIFE.eu :: ASCII Values Of Alphabets And Numbers In SQL Server

clock January 11, 2019 11:10 by author Peter

To find the ASCII value of an alphabet or a number, we can use ASCII function in SQL Server. We will see how to get the ASCII value of numbers from 0-9 and uppercase and lowercase alphabets.

What is ASCII?
ASCII (American Standard Code for Information Interchange) is the most common format for text files in computers and on the internet. In an ASCII file, each alphabetic, numeric, or special character is represented with a 7-bit binary number (a string of seven 0s or 1s). There can be 128 possible characters defined. It serves as a character encoding standard for modern computers.

Syntax
ASCII ( ‘character_expression’ )

ASCII value of capital A is 65 and Z 90.
    SELECT ASCII('A') 
    SELECT ASCII('Z') 


To find the ASCII values of alphabets from A to Z, use this code.

    DECLARE @Start int 
    set @Start=65 
    while(@Start<=90) 
    begin 
    print char(@Start) 
    set @Start=@Start+1 
    end 


To find the ASCII values of characters from a to z, we can use this query.
    SELECT ASCII('a') 
     
    SELECT ASCII('z') 
     
    DECLARE @Start int 
    set @Start=97 
    while(@Start<=122) 
    begin 
    print char(@Start) 
    set @Start=@Start+1 
    end 

ASCII Values Of Alphabets And Number In SQL Server

To find the ASCII value of numbers from 0 to 9, we can use this query.
    SELECT ASCII(9) 
     
    SELECT ASCII(0) 
     
    DECLARE @Start int 
    set @Start=48 
    while(@Start<=57) 
    begin 
    print char(@Start) 
    set @Start=@Start+1 
    end

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2016 Hosting - HostForLIFE.eu :: APPROX_COUNT_DISTINCT Function In SQL

clock January 7, 2019 11:13 by author Peter

Approximate COUNT DISTINCT

We all have written queries that use COUNT DISTINCT to get the unique number of non-NULL values from a table. This process can generate a noticeable performance hit especially for larger tables with millions of rows. Many times, there is no way around this. To help mitigate this overhead SQL Server 2019 introduces us to approximating the distinct count with the new APPROX_COUNT_DISTINCT function. The function approximates the count within a 2% precision to the actual answer at a fraction of the time.

Let’s see this in action.
In this example, I am using the AdventureworksDW2016CTP3 sample database which you can download here.
    SET STATISTICS IO ON 
    SELECT COUNT(DISTINCT([SalesOrderNumber])) as DISTINCTCOUNT 
    FROM [dbo].[FactResellerSalesXL_PageCompressed] 


SQL Server Execution Times
CPU time = 3828 ms, elapsed time = 14281 ms.
    SELECT APPROX_COUNT_DISTINCT ( [SalesOrderNumber]) as APPROX_DISTINCTCOUNT 
    FROM [dbo].[FactResellerSalesXL_PageCompressed] 


SQL Server Execution Times
CPU time = 7390 ms, elapsed time = 4071 ms.

APPROX_COUNT_DISTINCT Function In SQL

You can see the elapsed time is significantly lower! Great improvement using this new function.

The first time I did this, I did it wrong. A silly typo with a major result difference. So take a moment and learn from my mistake.

Note that I use COUNT(DISTINCT(SalesOrderNumber)) not DISTINCT COUNT (SalesOrderNumber ). This makes all the difference. If you do it wrong, the numbers will be way off as you can see from the below result set. You’ll also find that the APPROX_DISTINCTCOUNT will return much slower than the Distinct Count; which is not expected.

APPROX_COUNT_DISTINCT Function In SQL

Remember COUNT(DISTINCT expression) evaluates the expression for each row in a group and returns the number of unique, non-null values, which is what APPROX_COUNT_DISTINCT does. DISTINCT COUNT (expression) just returns a row count of the expression, there is nothing DISTINCT about it.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in