European Windows 2012 Hosting BLOG

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

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.

 



SQL Server 2016 Hosting - HostForLIFE.eu :: SQL Server Development Best Practices Guide

clock December 19, 2018 10:13 by author Peter

Coding is always a fun but challenging job. Developers do not only have to execute the right output based on the business requirement but also need to maintain the right coding standards by using the optimum use of variable sizes and keeping in view the other best practices. I am going to provide a list of best practices and guidelines today, in this article. Many of us already may have been using these but I thought to gather those in a single page so that while developing, the code can be useful, keeping the standard intact.
Application to be used,

  • Developers need to use the Developer Edition of the SQL Server edition rather than using SQL Express or Enterprise edition.

Database Design

  • Ensure that the referential integrity is maintained at all the times, i.e., the relationship between Primary Key and Foreign Key.
  • Always specify the narrowest columns you can. In addition, always choose the smallest data type you need to hold the data you need to store in a column. The narrower the column, the less amount of data SQL Server must store, and the faster SQL Server is able to read and write data.

Database Configuration Settings

  • Create proper database file sizes (this includes Initial DB file size and growth values)
  • Maintaining consistency in DB filegroups across the markets.

Data modeling

  • Use of appropriate data types and length while the data models are created (limit using blob data types unless really needed). The narrower the column, the less amount of data SQL Server must store, and the faster SQL Server is able to read and write data.

Performance/Load Tests

  • While performing perf tests, adjusts the database file sizes accordingly. Suspend the maintenance jobs during the period.

Purging solution

  • Checking with the business team over a period to implement the correct data purging solutions which best fits your environment.

Database Objects

  • Use user-defined constraint names rather using system-generated names.
  • Use database objects to sit in the respective defined Filegroups. Avoid getting the user objects and data to sit in the system/primary filegroup.

Indexing

  • Appropriate Index Naming convention.
  • Appropriate use of Case while creating objects such as tables, indexes and other objects.
  • Use the appropriate column sequence while creating the index schema.
  • Try to avoid creating duplicate indexes.
  • Limit use of filtered indexes unless you are sure that can give you real benefits.
  • When creating a composite index, and when all other considerations are equal, make the most selective column in the first column of the index.
  • keep the “width” of your indexes as narrow as possible. This reduces the size of the index and reduces the number of disks I/O reads required to read the index, boosting performance.
  • Avoid adding a clustered index to a GUID column (unique identifier data type). GUIDs take up 16-bytes of storage, more than an Identify column, which makes the index larger, which increases I/O reads, which can hurt performance.
  • Indexes should be considered on all columns that are frequently accessed by the JOIN, WHERE, ORDER BY, GROUP BY, TOP, and DISTINCT clauses.
  • Don't automatically add indexes on a table because it seems like the right thing to do. Only add indexes if you know that they will be used by queries run against the table. Always assess your workload before creating the right indexes.
  • When creating indexes, try to make them unique indexes if possible. SQL Server can often search through a unique index faster than a non-unique index because in a unique index, each row is unique, and once the needed record is found, SQL Server doesn't have to look any further.

Properties of Indexes

  • Don’t automatically accept the default value of 100 for the fill factor for your indexes. It may or may not best meet your needs. A high fill factor is good for seldom changed data, but highly modified data needs a lower fill factor to reduce page splitting.

Transact-SQL

  • If you perform regular joins between two or more tables in your queries, performance will be optimized if each of the joined columns has appropriate indexes.
  • Don't over-index your OLTP tables, as every index you add increases the time it takes to perform INSERTS, UPDATES, and DELETES. There is a fine line between having the ideal number of indexes (for SELECTs) and the ideal number to minimize the overhead that occurs with indexes during data modifications.
  • If you know that your application will be performing the same query over and over on the same table, consider creating a non-clustered covering index on the table. A covering index, which is a form of a composite index, includes all the columns referenced in SELECT, JOIN, and WHERE clauses of a query. Because of this, the index contains the data you are looking for and SQL Server doesn't have to look up the actual data in the table, reducing I/O, and boosting performance.
  • Remove encryption from table columns where it is not necessary at all. Overuse of encryption can lead to poor performance. Check with business users time to time on this to ensure right table columns are only considered for encryption.

Version control/source control

  • Maintain all code in a source control system and update it always for all type of changes happening to the code base.

Queries and Stored Procedures

  • Keep the transactions as short as possible. This reduces locking and increases the application concurrency, which helps to boost the performance.
  • If needed to run SQL commands use only designated columns rather using * to fetch all the commands and use the TOP operator to limit the number of records.
  • Avoid using query hints unless you know exactly what you are doing, and you have verified that the hint boosts performance. Instead, use the right isolation levels.
  • SET NOCOUNT ON at the beginning of each stored procedure you write.
  • Do not unnecessarily use select statements in the code block if you do not want to send any result back to display.
  • Avoid such code which can lead to unnecessary network calls. Check the count of the code block and verify if those many calls are really needed.
  • When using the UNION statement, keep in mind that, by default, it performs the equivalent of a SELECT DISTINCT on the result set. In other words, UNION takes the results of two like record sets, combines them, and then performs a SELECT DISTINCT in order to eliminate any duplicate rows. This process occurs even if there are no duplicate records in the final recordset. If you know that there are duplicate records, and this presents a problem for your application, then use the UNION statement to eliminate the duplicate rows.
  • If you see there is a necessity to use Upper () or Lower () functions or need to use LTRIM () or RTRIM () functions, it will be better to modify the data corrected while accepting the user inputs from the application side rather performing changes in the script. This will make the queries to run faster.
  • Carefully evaluate whether your SELECT query needs the DISTINCT clause or not. Some developers automatically add this clause to every one of their SELECT statements, even when it is not necessary.
  • In your queries, don't return column data you don't need. For example, you should not use SELECT * to return all the columns from a table if you don't need all the data from every column. In addition, using SELECT * may prevent the use of covering indexes, further potentially hurting query performance.
  • Always include a WHERE clause in your SELECT statement to narrow the number of rows returned. Only return those rows you need.
  • If your application allows users to run queries, but you are unable in your application to easily prevent users from returning hundreds, even thousands of unnecessary rows of data, consider using the TOP operator within the SELECT statement. This way, you can limit how many rows are returned, even if the user doesn't enter any criteria to help reduce the number of rows returned to the client.
  • Try to avoid WHERE clauses that are non-sargable. If a WHERE clause is sargable, this means that it can take advantage of an index (assuming one is available) to speed completion of the query. If a WHERE clause is non-sargable, this means that the WHERE clause (or at least part of it) cannot take advantage of an index, instead of performing a table/index scan, which may cause the query's performance to suffer. Non-sargable search arguments in the WHERE clause, such as "IS NULL", "<>", "!=", "!>", "!<", "NOT", "NOT EXISTS", "NOT IN", "NOT LIKE", and "LIKE '%500'" generally prevents (but not always) the query optimizer from using an index to perform a search. In addition, expressions that include a function on a column, expressions that have the same column on both sides of the operator, or comparisons against a column (not a constant), are not sargable. In such case, break the code appropriately so that a proper index or set of indexes can be used.
  • If using temporary tables to keep the backup of the existing large tables in the database, remove them as and when the task is needed as those contain a lot of storage and the maintenance plan will take more time to complete as because those tables will be considered for maintenance as well.
  • Do not use special characters or use them very carefully while passing them via a stored procedure. It might change the query execution plan and lead to poor performance. Often the situation is known as Parameter sniffing.
  • Avoid SQL server to do an implicit conversion of data, rather use it appropriately (use explicit code-based conversion).

SQL Server CLR
The Common language runtime (CLR) feature allows you to write stored procedures/trigger/functions in .NET managed code and execute the same from SQL Server.

  • Use the CLR to complement Transact-SQL code, not to replace it.
  • Standard data access, such as SELECT, INSERTs, UPDATEs, and DELETEs are best done via Transact-SQL code, not the CLR.
  • Computationally or procedurally intensive business logic can often be encapsulated as functions running in the CLR.
  • Use CLR for error handling, as it is more robust than what Transact-SQL offers.
  • Use CLR for string manipulation, as it is generally faster than using Transact-SQL.
  • Use CLR when you need to take advantage of the large base class library.
  • Use CLR when you want to access external resources, such as the file system, Event Log, a web service, or the registry.
  • Set CLR code access security to the most restrictive permissions as possible.

Consultation

  • You can also a consultant with your in-house DBAs for any advice about Microsoft Best Practices and standard or use of correct indexes to be used.
  • You can seek training from any good external training providers.
  • Another good option is to use good third-party tools such as RedGate, FogLight, Idera, SQLSentry, SolarWinds and check the performance of the environment by monitoring the scripts.

Process Improvement

  • Document common mistakes in the Lessoned Learned page per the PMP best practice guidelines.
  • Do check out the new upcoming editions and try to align your code accordingly.

Hope that the above-advised guidelines would be useful. Do share if you use any other steps in your workplace which is found to be helpful.

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



SQL Server 2016 Hosting - HostForLIFE.eu :: Maximum Limit Value For Integer Data Type in SQL Server 2012

clock November 27, 2018 10:12 by author Peter

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

Calculating the maximum range of various integer data types.

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

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

 

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

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

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

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

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

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

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

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

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

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

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

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

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

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



How To Split/Separate Numbers And Alphabets From Alpha Numeric String In SQL Server?

clock November 13, 2018 10:11 by author Peter

Today, I am going to explain how you can split/separate numbers and alphabets from an alphanumeric string in SQL server. When you work with any database-related application, either in Web or Windows applications, sometimes based on your requirement you have an alphanumeric string and you only want numbers from that string and want to use those numbers in your entire application as per your need, possibly as a variable, parameter, or a string concatenation.

Implementation
In my case I want to generate auto-increment token number and that token number will generate with a combination of My Invoice Number and Heder Name of Store, and in my Invoice Table Invoice Number like "HSP14569" where "HSP" is Header Name of Store. That can change based on Store selection and "14569" is my Invoice Number.

Actually, what I need is to split my invoice number from "HSP14569" To "14569" and increment with "1," so that will be "14570". Now, I will contact this new number with my header of the store.

So, yesterday I wrote one user-defined function in SQL server, which will return only numeric values from my string.

SQL Server User Defined Function
    CREATE FUNCTION dbo.GetNumericValue 
    (@strAlphaNumeric VARCHAR(256)) 
    RETURNS VARCHAR(256) 
    AS 
    BEGIN 
    DECLARE @intAlpha INT 
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric) 
    BEGIN 
    WHILE @intAlpha > 0 
    BEGIN 
    SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' ) 
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric ) 
    END 
    END 
    RETURN ISNULL(@strAlphaNumeric,0) 
    END 
    GO 


Note
You can modify this user defined function based on your need.

Let's see how you can use this user-defined function. Below, I have included some of the ways to use this function.
 
Sql Server Select Statment
    SELECT dbo.GetNumericValue('') AS 'Empty'; 
    SELECT dbo.GetNumericValue('HSP14569AS79RR5') AS 'Alpha Numeric'; 
    SELECT dbo.GetNumericValue('14569') AS 'Numeric'; 
    SELECT dbo.GetNumericValue('HSP') AS 'String'; 
    SELECT dbo.GetNumericValue(NULL) AS 'NULL'; 


Output

Summary
You can see the result was generated as above. If you have some alternate way to achieve this kind of requirement then please let me know, or if you have some query then please leave your comments.

 

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



SQL Server 2016 Hosting - HostForLIFE.eu :: All About Primary Key And Its Basics

clock November 7, 2018 08:44 by author Peter

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

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

Find all Primary key in Give Database in following format,

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


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

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


Detailed level relationship and description of primary key and foreign key

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


Use the above snippets as per your requirement.

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

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

 

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



SQL Server 2016 Hosting - HostForLIFE.eu :: How To Check If A String Contains A Substring In SQL Server?

clock November 2, 2018 12:14 by author Peter

In this blog, I wil explain how to check a specific word or character in a given statement in SQL Server, using CHARINDEX function or SQL Server and check if the string contains a specific substring with CHARINDEX function.
 
Alternative to CHARINDEX() is using LIKE predicate.
 
Method 1 - Using CHARINDEX() function

CHARINDEX()
This function is used to search for a specific word or a substring in an overall string and returns its starting position of match. In case no word is found, then it will return 0 (zero).
 
Let us understand this with examples.

Syntax
    CHARINDEX ( SearchString,WholeString[ , startlocation ] )

Example
    Declare @mainString nvarchar(100)='Kenneth James    ' 
    ---Check here @mainString contains Kenneth or not, if it contains then retrun greater than 0 then print Find otherwise Not Find 
    if CHARINDEX('Kenneth',@mainString) > 0  
    begin 
       select 'Find' As Result 
    end 
    else 
        select 'Not Find' As Result 


Output

CHARINDEX
 
Method 2 - Using LIKE Predicate
    DECLARE @WholeString VARCHAR(50) 
    DECLARE  @ExpressionToFind VARCHAR(50) 
    SET @WholeString = 'Kenneth James' 
    SET @ExpressionToFind = 'James' 
      
    IF @WholeString LIKE '%' + @ExpressionToFind + '%' 
        PRINT 'Yes it is find' 
    ELSE 
        PRINT 'It doesn''t find' 

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 :: Identity Column In SQL Server

clock October 23, 2018 11:42 by author Peter
In this article, we will learn about identity function and how we reset identity columns in SQL Server. Identity keyword is used in SQL Server to auto increment column value.
Identity is a function which can be used to generate unique id values of a particular column automatically. It can be applied on integer datatype column only. A table should contain only one identity column.

Syntax
identity(seed,increment)
Default value of identity is identity (1,1)

The seed represents the starting value of an ID and the default value of seed is 1.

Increment: It will represent the incremental value of the ID and the default value of increment is 1.

Example

Create table student(Id int Primary key Identity ,Name varchar(50),City varchar(50),TotalNumer int)  
insert into student(Name,City,TotalNumer) values('A','Delhi',120)  
insert into student(Name,City,TotalNumer) values('B','Noida',110)  
insert into student(Name,City,TotalNumer) values('C','Gurgaon',125)  
select * from student  

Check the table, ID value is increased automatically. The default value of identity is the identity (1,1) ID column starts with 1 and increased by 1.

Example
User defined seed and incremental values,

create table tec(Id int identity(10,5),Deptname varchar(50))  
insert tec values('Dot Net')  
insert tec values('SQL')  
select * from tec 

Id value starts by 10 and increases by 5.

Note
If we want to insert the values into an identity column explicitly then we should follow the syntax.

Set identity_insert <Table name> off/on

Off-It is a default connection; we cannot insert a value into an identity column explicitly.

On-we can insert the values into an identity column explicitly. 

Reset Identity Column
Syntax
dbcc checkident('table name',reseed,0)
 
We can reseed identity column value using the DBCC CHECKIDENT command of SQL. Using this command we can reset identity column values,
dbcc checkident('student',reseed,0)

In this article, we have learned about identity column in SQL Server and how we can reset identity column values.

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 :: Resolving The "Wait Operation Timed Out" Error When TFS Stops Working

clock October 17, 2018 11:48 by author Peter

Today, I will share one more interesting issue. A few days ago, our system administrator installed the Microsoft Test Manager 2012 on Microsoft Team Foundation Server 2010 (TFS 2010). Suddenly, our TFS stopped working. TFS was not able to extract the data from the database. Then I checked the error in the Event Viewer and found the error as below.

I did confirm that all the services inside the SQL Server were working fine. It became very difficult to find out the cause of this error because in our environment, SharePoint Server also existed and it was using the same SQL Server and working fine. After searching a lot about it on the internet, I found somewhere that the people got the same error after installing the Visual Studio 2011 and Visual Studio 2012.
 
Finally, I got the solution. I removed “.NET FrameWork 4.5″ from the system and reinstalled the ”.NET FrameWork 4.0". Then, our TFS Server went up again and started running fine. But it wasted a lot of time to find this solution, so, I am posting this it here to help people. However, I would advise you to be careful before making any changes or installing something new on the running server.

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