Sunday, December 1, 2019

Corelated Subquries

Correlated subqueries are used for row-by-row processing. Each subquery is executed once for every row of the outer query.
SQL_Correlated_Subqueries
A correlated subquery is evaluated once for each row processed by the parent statement. The parent statement can be a SELECTUPDATE, or DELETE statement.

SELECT column1, column2, ....
FROM table1 outer
WHERE column1 operator
                    (SELECT column1, column2
                     FROM table2
                     WHERE expr1 = 
                               outer.expr2);
A correlated subquery is one way of reading every row in a table and comparing values in each row against related data. It is used whenever a subquery must return a different result or set of results for each candidate row considered by the main query. In other words, you can use a correlated subquery to answer a multipart question whose answer depends on the value in each row processed by the parent statement.

Nested Subqueries Versus Correlated Subqueries :

With a normal nested subquery, the inner SELECT query runs first and executes once, returning values to be used by the main query. A correlated subquery, however, executes once for each candidate row considered by the outer query. In other words, the inner query is driven by the outer query.
NOTE : You can also use the ANY and ALL operator in a correlated subquery.
EXAMPLE of Correlated Subqueries : Find all the employees who earn more than the average salary in their department.


SELECT last_name, salary, department_id
 FROM employees outer
 WHERE salary >
                (SELECT AVG(salary)
                 FROM employees
                 WHERE department_id =
                        outer.department_id);
Other use of correlation are in UPDATE and DELETE

CORRELATED UPDATE :

UPDATE table1 alias1
 SET column = (SELECT expression 
               FROM table2 alias2
               WHERE alias1.column =
                     alias2.column);
Use a correlated subquery to update rows in one table based on rows from another table.

CORRELATED DELETE :

DELETE FROM table1 alias1
 WHERE column1 operator
               (SELECT expression
                FROM table2 alias2
                WHERE alias1.column = alias2.column);
Use a correlated subquery to delete rows in one table based on the rows from another table.

Using the EXISTS Operator :

The EXISTS operator tests for existence of rows in the results set of the subquery. If a subquery row value is found the condition is flagged TRUE and the search does not continue in the inner query, and if it is not found then the condition is flagged FALSE and the search continues in the inner query.
EXAMPLE of using EXIST operator :
Find employees who have at least one person reporting to them.

SELECT employee_id, last_name, job_id, department_id
FROM employees outer
WHERE EXISTS ( SELECT ’X’
FROM employees
WHERE manager_id =
outer.employee_id);

https://www.geeksforgeeks.org/sql-correlated-subqueries/

Cross Apply

Microsoft introduced the APPLY operator in SQL Server 2005. The APPLY operator is similar to the T-SQL JOIN clause as it also allows you to join two tables – for example, you can join an outer table with an inner table. The APPLY operator is a good option when, on one side, we have a table-evaluated expression that we want to evaluate for each row from the table we have on another side. So, the right-side table is processed for each row of the left-side table. The left-side table is evaluated first, and then the right-side table is evaluated against each row of the left-side table to generate the final result set. The final result set includes all columns from both tables.

The APPLY operator has two variations:

  • CROSS APPLY
  • OUTER APPLY

CROSS APPLY

CROSS APPLY is similar to INNER JOIN, but can also be used to join table-evaluated functions with SQL Tables. CROSS APPLY’s final output consists of records matching between the output of a table-evaluated function and an SQL Table.

OUTER APPLY

OUTER APPLY resembles LEFT JOIN, but has an ability to join table-evaluated functions with SQL Tables. OUTER APPLY’s final output contains all records from the left-side table or table-evaluated function, even if they don’t match with the records in the right-side table or table-valued function.

-----

Starting with SQL Server 2005, you can use the APPLY operator in a Transact-SQL query to join a table to a table-valued function so the function is evoked for each row returned from the table. For example, you might create a query that returns a list of employees from the Employee table. For each employee, you also want to return a list of the individual job positions that person has held in the company.
You can create a function that retrieves the employees’ positions and then evoke that function for each row returned from the Employee table. Your result set will then include a row for each position that an employee has held. For instance, if John has worked as a salesman and a regional supervisor, the result set will include two rows for John, one for each position. Any data returned from the Employee table will be repeated for each row, but the data returned by the function will be specific to each row in the function’s results.

https://www.red-gate.com/simple-talk/sql/t-sql-programming/sql-server-apply-basics/

https://codingsight.com/advanced-sql-cross-apply-and-outer-apply/

Saturday, November 30, 2019

Interview

1. What is Cross Apply in SQL Server?
2. How to test Singleton class?

[TestMethod()]
public void ReturnConnTest()
{
    SClass target = new SClass(); 
    string expected = "This is MOQ class"; 
    string actual;
    Mock<SClass> moqClass = new Mock<SClass>();
    moqClass.Setup(mc => mc.ReturnConn()).Returns(expected);
    target = moqClass.Object;
    actual = target.ReturnConn();
    Assert.AreEqual(expected, actual);
}
3. Difference between Dependency Injection and Inversion of control.

Here is an informal definition of IoC: “IoC is when you have someone else create objects for you.” So instead of writing “new MyObject” in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container.

This simple explanation illustrates some very important ideas:

  1. It is called IoC because control of the object is inverted. It is not the programmer, but someone else who controls the object.
  2. IoC is relative in the sense that it only applies to some objects of the application. So there may be IoC for some objects, whereas others are under the direct control of the programmer.
DI is one of the subtypes of the IOC principle  

We can achieve Inversion of Control through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).

Inversion of Control(IoC) is a principle by which the control of objects is transferred to a container or framework. Dependency injection is a pattern through which IoC is implemented and the act of connecting objects with other objects or injecting objects into objects is done by container rather than by the object themselves.




Friday, November 8, 2019

What is An Auxiliary Route?


A component has one primary route and zero or more auxiliary routes.. Auxiliary routes allow you to use and navigate multiple routes. To define an auxiliary route you need a named router outlet where the component of the auxiliary route will be rendered.

The name that we're giving to the second outlet suggests that the outlet will be used as a sidebar for the app.

--------

Each component has one primary route and zero or more auxiliary outlets. Auxiliary outlets must have unique name within a component.

To define the auxiliary route we must first add a named router outlet where contents for the auxiliary route are to be rendered.

Here's an example:

import {Component} from '@angular/core';
@Component({
selector: 'app',
template: `
<nav>
<a [routerLink]="['/component-one']">Component One</a>
<a [routerLink]="['/component-two']">Component Two</a>
<a [routerLink]="[{ outlets: { 'sidebar': ['component-aux'] } }]">Component Aux</a>
</nav>
<div style="color: green; margin-top: 1rem;">Outlet:</div>
<div style="border: 2px solid green; padding: 1rem;">
<router-outlet></router-outlet>
</div>
<div style="color: green; margin-top: 1rem;">Sidebar Outlet:</div>
<div style="border: 2px solid blue; padding: 1rem;">
<router-outlet name="sidebar"></router-outlet>
</div>
`
})
export class AppComponent {
}

Next we must define the link to the auxiliary route for the application to navigate and render the contents.

<a [routerLink]="[{ outlets: { 'sidebar': ['component-aux'] } }]">
Component Aux
</a>

View Example

Each auxiliary route is an independent route which can have:

  • its own child routes

  • its own auxiliary routes

  • its own route-params

  • its own history stack


https://www.techiediaries.com/angular-router-multiple-outlets/

Wednesday, September 4, 2019

Difference between Redirect and RedirectToAction

RedirectToAction lets you construct a redirect url to a specific action/controller in your application, that is, it'll use the route table to generate the correct URL.
Redirect requires that you provide a full URL to redirect to.
If you have an action Index on controller Home with parameter Id:
  1. You can use RedirectToAction("Index", "Home", new { id = 5 }) which will generate the URL for you based on your route table.
  2. You can use Redirect but must construct the URL yourself, so you pass Redirect("/Home/Index/5") or however your route table works.
  3. You can't redirect to google.com (an external URL) using RedirectToAction, you must use Redirect.
RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table.
Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.
Best Practices: Use RedirectToAction for anything dealing with your application actions/controllers. If you use Redirect and provide the URL, you'll need to modify those URLs manually when your route table changes.

https://www.dotnettricks.com/learn/mvc/return-view-vs-return-redirecttoaction-vs-return-redirect-vs-return-redirecttoroute

Monday, September 2, 2019

Count positive and Negative number

Count positive and Negative number

select Positive = count(case when num>0 then 1 else null end), negative =count(case when num<0 1="" else="" end="" from="" null="" p="" temp="" then="">
Ques : How to create backup table using query
Ans : Select * into table1 from table2.

Ques : How to get emp name whose salary is greater than average salary in the department?

;with as temp1(id, salary)
as
(
    select id avg(salary) as averagesalary from temp group by id
 )   
  select id from temp1 inner join on temp.id=temp1.id where salary>averagesalary  select * from emp e, (select dept,avg(sal) avg_sal from emp group by dept) e1 where e.dept=e1.dept and e.sal > e1.avg_sa

Friday, August 23, 2019

ECMAScript 6 modules


In the new version of JavaScript, ECMAScript 6 (also known as ES6), native modules have been introduced. Thefollowing points are some of the most important aspects of these modules:
  • Module code always automatically runs in strict mode
  • Variables that are created in the top level of a module are not added to the global scope
  • A module must export anything that should be available to the outside code
  • A module can import bindings (things that are exported from other modules)
The main idea behind modules in ES6 is to give you complete control over what is accessible to the outside code from inside the module, as well as when the code inside of the module is executed.
Let's have a look at a simple example of an ES6 module.

Defining an ES6 module

We can define an ES6 module either inside of a .js file, or inside a 

CommonJS



CommonJS

As with AMD format, CommonJS (also known as CJS) is another format which defines JavaScript modules as objects that can be made available to any dependent code. CJS modules can only define objects, as opposed to AMD modules, which can define constructors and functions too.
Unlike AMD format, which takes a browser-first approach, CommonJS takes a server-first approach. It also covers a broader set of concerns which are server-related, such as io, file system, and alike.
Many developers (I'm one of them) use AMD format for browser-targeted modules and CommonJS for server-side targeted modules. However, you could use CJS format for browser modules as well.
Some of the tools that support CJS for the browsers are:
Let's have a look at a simple example to see how we can implement a CJS format module.

Implementing a CommonJS module

Imagine that we have a file called moduleOne.js. From inside this file, we can export...

AMD

Introducing Asynchronous Module Definition

Asynchronous Module Definition (AMD) format for creating modules in JavaScript, is targeted for use in browsers. This format proposes a particular way for defining modules so that modules and their dependencies can be loaded into the browser asynchronously.
There are two key methods that you need to use when creating and consuming AMD modules, these are defineand require methods.
The idea is that we create a module using the global define method and then we can import that module in other parts of the code (other modules) using the global require method.

Defining modules using AMD format

Here is how a module can be defined in AMD format:
define('moduleOneId', ['dependency'], function(dependency) {

    return {
        sayHi: function(){
            console.log('Hi there!')
        }
    }
});
In the preceding code, we are passing three arguments to the global define method, which has been provided to us by an AMD-compatible module loader.

https://subscription.packtpub.com/book/web_development/9781785880650/10/ch10lvl1sec54/introducing-asynchronous-module-definition

Tuesday, August 20, 2019

Difference Between Dapper and ADO .Net

ADO.NET, for example, won't give you objects (or, at best, will only give you a pseudo object like a DataTable) While Dapper allow to work with classes. Dapper is a wrapper on ADO .net

public class ADONET : ITestSignature
{
    public long GetPlayerByID(int id)
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        using(SqlConnection conn = new SqlConnection(Constants.ConnectionString))
        {
            conn.Open();
            using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT Id, FirstName, LastName, DateOfBirth, TeamId FROM Player WHERE Id = @ID", conn))
            {
                adapter.SelectCommand.Parameters.Add(new SqlParameter("@ID", id));
                DataTable table = new DataTable();
                adapter.Fill(table);
            }
        }
        watch.Stop();
        return watch.ElapsedMilliseconds;
    }

}

public class Dapper : ITestSignature
{
    public long GetPlayerByID(int id)
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        using (SqlConnection conn = new SqlConnection(Constants.ConnectionString))
        {
            conn.Open();
            var player = conn.Query("SELECT Id, FirstName, LastName, DateOfBirth, TeamId FROM Player WHERE Id = @ID", new{ ID = id});
        }
        watch.Stop();
        return watch.ElapsedMilliseconds;
    }
}

Entityframework vs Dapper






Entity Framework (EF) and Dapper both are object-relational mappers that enable .NET developers to work with relational data using domain-specific objects. Dapper owns the title of King of Micro ORM in terms of performance.

"Micro-ORMs" like Dapper.NET (which is used on the StackExchange family of sites including StackOverflow) which promise performance at the cost of maintainability.
 The major drawback to using Dapper.NET is that you have naked SQL queries in your code.

Entity Framework

Advantages

  • Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer and generate a new database.
  • You can write code against the Entity Framework, and the system will automatically produce objects for you as well as track changes on those objects and simplify the process of updating the database.
  • One common syntax (LINQ) for all object queries whether it is a database or not and pretty fast if used as intended, easy to implement and less coding required to accomplish complex tasks.
  • The EF can replace a large chunk of code you would otherwise have to write and maintain yourself.
  • It provides auto-generated code
  • It reduces development time and cost.
  • It enables developers to visually design models and mapping of database

Disadvantages

  • You have to think in a non-traditional way of handling data, not available for every database.
  • If there is any schema change in database FE won't work and you have to update the schema in solution as well.
  • The EF queries are generated by the provider that we cannot control.
  • It is not good for a huge domain model.
  • Lazy loading is the main drawbacks of EF

Dapper

Advantages

  • Dapper make it easy to correctly parameterize queries
  • It can easily execute queries (scalar, multi-rows, multi-grids, and no-results)
  • Make it easy to turn results into objects
  • It is very efficient and owns the title of King of Micro ORM in terms of performance.

Disadvantages

  • Dapper can't generate a class model for you
  • It cannot generate queries for you
  • It cannot track objects and their changes
  • The raw dapper library doesn't provide CRUD features, but the "contrib" additional package does provide basic CRUD.



Followers

Link