Pages

Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Saturday, April 21, 2012

SQL Custom Paging


Using SQL Server Stored Procedure for implementing Custom Paging:

All of us would have implemented Paging in our applications.


Paging is particularly useful if you have lots of records to be displayed on a page and you can't get them displayed in one stretch. Say we have 1000 records to be displayed in a page. In this scenario, we cannot show up all the records in a single stretch in the page. Hence we need to implement Paging functionality whereby users can see a set of records and then click on a Button/Link to view the next set of records.

Here is the sample store procedure that is used for the SQL Server store procedure for paging.
Example:
CREATE PROCEDURE USP_PRODUCT_SELECT
(
@CurrentIndex int,
@TotalPageSize int
)
 AS

SELECT * FROM
(

SELECT ROW_NUMBER() OVER(ORDER BY ProductID) AS RowId, * FROM Products

) AS  P
WHERE  P.RowId BETWEEN (@CurrentIndex -1) * @TotalPageSize+ 1 AND (@CurrentIndex  * @TotalPageSize )
GO

#SQL Server, #Custom Paging

Recursive Query In Sql Server

A common table expression (CTE) provides the significant advantage of being able to reference itself, thereby creating a recursive CTE. A recursive CTE is one in which an initial CTE is repeatedly executed to return subsets of data until the complete result set is obtained.

A query is referred to as a recursive query when it references a recursive CTE. Returning hierarchical data is a common use of recursive queries, for example: Displaying employees in an organizational chart, or data in a bill of materials scenario in which a parent product has one or more components and those components may, in turn, have subcomponents or may be components of other parents.
A recursive CTE can greatly simplify the code required to run a recursive query within a SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. In earlier versions of SQL Server, a recursive query usually requires using temporary tables, cursors, and logic to control the flow of the recursive steps.

The structure of the recursive Query


The structure of the recursive CTE in Transact-SQL is similar to recursive routines in other programming languages. Although a recursive routine in other languages returns a scalar value, a recursive CTE can return multiple rows.
A recursive CTE consists of three elements:
  1. Invocation of the routine.
    The first invocation of the recursive CTE consists of one or more CTE_query_definitions joined by UNION ALL, UNION, EXCEPT, or INTERSECT operators. Because these query definitions form the base result set of the CTE structure, they are referred to as anchor members.
    CTE_query_definitions are considered anchor members unless they reference the CTE itself. All anchor-member query definitions must be positioned before the first recursive member definition, and a UNION ALL operator must be used to join the last anchor member with the first recursive member.
  2. Recursive invocation of the routine.
    The recursive invocation includes one or more CTE_query_definitions joined by UNION ALL operators that reference the CTE itself. These query definitions are referred to as recursive members.
  3. Termination check.
    The termination check is implicit; recursion stops when no rows are returned from the previous invocation.
Recursive query in sql server Example:

WITH  CTE(categoryId,CategoryName,ParentCategoryID,TopParentCategoryID) AS
(
SELECT    
a.CategoryId,
a.CategoryName,
a.ParentCategoryID, 
a.CategoryId AS TopParentCategoryID
FROM Categories  a WHERE  ParentCategoryID is null
UNION ALL
SELECT c.CategoryId, c.CategoryName, c.ParentCategoryID, cte.TopParentCategoryID AS TopParentCategoryID FROM Categories c,cte
WHERE cte.CategoryId = c.ParentCategoryID
)
SELECT CTE.categoryId,cte.CategoryName,cte.ParentCategoryID,cte.TopParentCategoryID FROM CTE


Wednesday, June 24, 2009

calculate hour minutes from milliseconds in oracle query

SQL QUERY:

SELECT
SUBSTR(to_char((39600/60/60),'00.00') , 0, INSTR(to_char((39600/60/60),'00.00'), '.', 1, 1)-1) hour,
to_char((SUBSTR(to_char((39600/60/60),'00.00'), INSTR(to_char((39600/60/60),'00.00'), '.', 1, 1),length(to_char((39600/60/60),'00.0'))) *60),'00') as Minutes
FROM dual;

OUTPUT

HOUR MINUTES
------ -------
11 00

1 rows selected

ANOTHER EXAMPLE

SELECT
SUBSTR(to_char((11700/60/60),'00.00') , 0, INSTR(to_char((11700/60/60),'00.00'), '.', 1, 1)-1) hour,
to_char((SUBSTR(to_char((11700/60/60),'00.00'), INSTR(to_char((11700/60/60),'00.00'), '.', 1, 1),length(to_char((11700/60/60),'00.00'))) *60),'00') as Minutes
FROM dual;

OUTPUT

HOUR MINUTES
------ -------
03 15

1 rows selected

Wednesday, May 13, 2009

How To Get List of Tables in SQL Server


Using Following SQL Query you can get list of tables in SQL Database

SELECT name [Table Name]
FROM sysobjects
WHERE xtype = 'U'



How to Get SQL Table Columns List

How to get all field names in a table using sql query?



Following query is use for getting all sql table column names from database in Microsoft SQL server.

SELECT c.name
FROM syscolumns c INNER JOIN sysobjects o ON o.id = c.id
WHERE o.name ='TABLENAME'
ORDER BY colid

#How to find all SQL tables with a column name
#How to Get SQL Table Columns List
#How to get all field names in a table using sql query

Thursday, April 23, 2009

sql query for Generate serial no



SELECT C.EmployeeId, C.FirstName,C.LastName,

(SELECT COUNT(*) FROM Employee C2 WHERE C2.EmployeeId <= C.EmployeeId

) as SrNoFROM Employee C ORDER BY EmployeeId

Friday, April 17, 2009

restrict delete record which is used in other table in mssql

1. Create Scalar value Function in sql
ex:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go



create FUNCTION [dbo].[GetApplicationDelete]
(
@ApplicationId numeric(18,0)
)
RETURNS bit
AS
BEGIN
-- Declare the return variable here
DECLARE @flg as bit;
declare @count as numeric(18,0);

-- Add the T-SQL statements to compute the return value here
select @count = SUM(b) from
(
SELECT count(*) b from dbo.ApplicationApprover
where ApplicationId = @ApplicationId
union
select count(*) b from .dbo.Cases
where ApplicationId = @ApplicationId



) tablename

if @count = 0
set @flg =1;
else
set @flg =0;


-- Return the result of the function
RETURN @flg

END

2 .Use this function in Sql Query

Ex:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go




create PROCEDURE [dbo].[APPLICATION_FindAll]
AS
SET NOCOUNT ON

SELECT
ApplicationId,
AppCode,
AppName,
Description,
Remarks,
AppType,
IsActive,
IsDelete,
AppStartdate,
AppEnddate,
CreateBy,
CreateDate,
UpdateBy,
UpdateDate,
[dbo].GetApplicationDelete(ApplicationId) delflg
FROM [APPLICATION]

GO

3. Apply in Form in Grid View Delete Button
<asp:TemplateField HeaderText="Delete">

<ItemTemplate>

<asp:ImageButton ID="imgbtnDelete" runat="server" AlternateText="Delete" CausesValidation="False"

CommandName="Delete" ImageUrl="~/App_Themes/Image/Delete.gif" OnClientClick="Are You Sure?"

Visible='<%# Eval("delflg") %>' />

</ItemTemplate>

<ItemStyle HorizontalAlign="Center" />

</asp:TemplateField>

Wednesday, March 18, 2009

Types of SQl Join

The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.
Look at the "Persons" table:
P_Id LastName FirstName Address City
1 Rajesh Ahmedabad Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.
Next, we have the "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to the persons in the "Persons" table without using their names.
Notice that the relationship between the two tables above is the "P_Id" column.

Different SQL JOINs

Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.
  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

The INNER JOIN keyword return rows when there is at least one match in both tables.

SQL INNER JOIN Syntax

SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
PS: INNER JOIN is the same as JOIN.

SQL INNER JOIN Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Rajesh Ahmedabad Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
The "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons with any orders.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName 
The result-set will look like this:
LastName FirstName OrderNo
Rajesh Ahmedabad 22456
Rajesh Ahmedabad 24562
Pettersen Kari 77895
Pettersen Kari 44678
The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in "Persons" that do not have matches in "Orders", those rows will NOT be listed.

SQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).

SQL LEFT JOIN Syntax

SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).

SQL RIGHT JOIN Syntax

SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

SQL FULL JOIN Keyword

The FULL JOIN keyword return rows when there is a match in one of the tables.

SQL FULL JOIN Syntax

SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

ShareThis

Welcome

Welcome to Rajesh Prajapati, asp.net blog.
Here you can find some useful code and information about asp.net., c#, VB.net, SQL Server, Web Service, Web Designing etc