Showing posts with label table. Show all posts
Showing posts with label table. Show all posts

Friday, 23 August 2013

SQL Server Basics of Cursors

Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time. We use cursor when we need to update records in a database table in singleton fashion means row by row.

Life Cycle of Cursor

  1. Declare Cursor

    A cursor is declared by defining the SQL statement that returns a result set.
  2. Open

    A Cursor is opened and populated by executing the SQL statement defined by the cursor.
  3. Fetch

    When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.
  4. Close

    After data manipulation, we should close the cursor explicitly.
  5. Deallocate

    Finally, we need to delete the cursor definition and released all the system resources associated with the cursor.

Syntax to Declare Cursor

Declare Cursor SQL Comaand is used to define the cursor with many options that impact the scalablity and loading behaviour of the cursor. The basic syntax is given below
  1. DECLARE cursor_name CURSOR
  2. [LOCAL | GLOBAL] --define cursor scope
  3. [FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward)
  4. [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor
  5. [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks
  6. FOR select_statement --define SQL Select statement
  7. FOR UPDATE [col1,col2,...coln] --define columns that need to be updated

Syntax to Open Cursor

A Cursor can be opened locally or globally. By default it is opened locally. The basic syntax to open cursor is given below:
  1. OPEN [GLOBAL] cursor_name --by default it is local

Syntax to Fetch Cursor

Fetch statement provides the many options to retrieve the rows from the cursor. NEXT is the default option. The basic syntax to fetch cursor is given below:
  1. FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n]
  2. FROM [GLOBAL] cursor_name
  3. INTO @Variable_name[1,2,..n]

Syntax to Close Cursor

Close statement closed the cursor explicitly. The basic syntax to close cursor is given below:
  1. CLOSE cursor_name --after closing it can be reopen

Syntax to Deallocate Cursor

Deallocate statement delete the cursor definition and free all the system resources associated with the cursor. The basic syntax to close cursor is given below:
  1. DEALLOCATE cursor_name --after deallocation it can't be reopen

SQL SERVER – Simple Examples of Cursors

  1. CREATE TABLE Employee
  2. (
  3. EmpID int PRIMARY KEY,
  4. EmpName varchar (50) NOT NULL,
  5. Salary int NOT NULL,
  6. Address varchar (200) NOT NULL,
  7. )
  8. GO
  9. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
  10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi')
  11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun')
  12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
  13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon')
  14. GO
  15. SELECT * FROM Employee

  1. SET NOCOUNT ON
  2. DECLARE @Id int
  3. DECLARE @name varchar(50)
  4. DECLARE @salary int
  5. DECLARE cur_emp CURSOR
  6. STATIC FOR
  7. SELECT EmpID,EmpName,Salary from Employee
  8. OPEN cur_emp
  9. IF @@CURSOR_ROWS > 0
  10. BEGIN
  11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
  12. WHILE @@Fetch_status = 0
  13. BEGIN
  14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary)
  15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
  16. END
  17. END
  18. CLOSE cur_emp
  19. DEALLOCATE cur_emp
  20. SET NOCOUNT OFF

Friday, 9 August 2013

Create Table with same Columns of existing table

Hey...try this Sql Query to create new table with same schema as existing table

"select * into newtable from existingtable"

Friday, 19 July 2013

Create Table in SQL Server 2008 using Query

Create table table1(
col1 int identity primary key,
col2 nvarchar(20),
col3 nvarchar(100),
Date datetime default getdate()
)

Create Stored Procedure using Case and Conditional Satatment in SQL Server 2008

Example:............for Stored Procedure...

Create proc [dbo].[sp_Order_Confirm]        
@Buy_Sell_Ind INT,        
@orderId NUMERIC(10,0),        
@price NUMERIC(9,2)=0,        
@code nCHAR(20),        
@cwhere VARCHAR(200)='',
@OptionType nchar(1)=''        
AS        
BEGIN        
 if @cwhere='RL'      
 begin      
 declare @sPrice numeric(9,2)    
 declare @bPrice numeric(9,2)  
 declare @ltp numeric(9,2)
 -------------------------------when price between Buy sell
   IF EXISTS(SELECT * FROM dbo.Product_Det WHERE ScripCode=@code AND @Buy_Sell_Ind=1 AND (convert(numeric(9,2),SellPrice)= convert(numeric(9,2),@price)OR convert(numeric(9,2),LastTradedPrice)= convert(numeric(9,2),@price))  OR ScripCode=@code AND @Buy_Sell_Ind=2 AND (convert(numeric(9,2),BuyPrice) = convert(numeric(9,2),@price)OR convert(numeric(9,2),LastTradedPrice) = convert(numeric(9,2),@price)) )        
   BEGIN      
   UPDATE dbo.ORDER_File SET confirmed='1' WHERE Order_Number=@orderId        
   END        
     -----------------------------------  end beween price
     
     ---------------------------------------------- buy confirmed when  price greater than sell price
     ----------------------------------------------sell confirmed when prive smaller than Buy price
       IF EXISTS(SELECT * FROM dbo.Product_Det WHERE ScripCode=@code AND @Buy_Sell_Ind=1 AND (convert(numeric(9,2),SellPrice) < convert(numeric(9,2),@price)OR convert(numeric(9,2),LastTradedPrice) < convert(numeric(9,2),@price)OR convert(numeric(9,2),@price)=convert(numeric(9,2),0))
       OR ScripCode=@code AND @Buy_Sell_Ind=2 AND (convert(numeric(9,2),BuyPrice) > convert(numeric(9,2),@price) OR convert(numeric(9,2),LastTradedPrice) > convert(numeric(9,2),@price) ))        
   BEGIN          
    SELECT @sPrice=CONVERT(NUMERIC(9,2),sellprice),@bPrice=CONVERT(NUMERIC(9,2),buyprice),@ltp=convert(numeric(9,2),LastTradedPrice) FROM dbo.Product_Det WHERE ScripCode=@code AND @Buy_Sell_Ind=1  OR ScripCode=@code AND @Buy_Sell_Ind=2    
 
    UPDATE dbo.ORDER_File SET confirmed='1' ,    
          price=case when ( @Buy_Sell_Ind=1 and @OptionType='') then @sPrice
          when (@Buy_Sell_Ind=1 and @OptionType='4') then @price    
          when (@Buy_Sell_Ind=2 and @OptionType='')  then @bPrice
          when (@Buy_Sell_Ind=2 and @OptionType='5') then  @price
      end    
     WHERE Order_Number=@orderId        
     END  
     --------------------------------  end smaller n greater than condition
     -------------------------------end smaller n greater than condition
       
    end    ---RL end  
   
   
   ------------------------trigger price condition
         
    else if @cwhere='SL'    
   begin      
    IF EXISTS(SELECT * FROM dbo.Product_Det WHERE ScripCode=@code AND @Buy_Sell_Ind=1 AND convert(numeric(9,2),SellPrice)=convert(numeric(9,2),@price) OR ScripCode=@code AND @Buy_Sell_Ind=2 AND convert(numeric(9,2),BuyPrice) = convert(numeric(9,2),@price)
)        
    BEGIN        
      UPDATE dbo.ORDER_File SET confirmed='1' WHERE Order_Number=@orderId        
    END      
 end      --end trigger
      ---------------------------------------------------------------  
END

Create table valued function in SQL Server 2008

Example:      Table valued function.............

CREATE function [dbo].[sp_TotalPending](@contract_code nvarchar(150),@buySell nvarchar(50),@tablefetch nvarchar(150))
returns @resultTable table
(
 totalVolumn int
)
as
begin

declare @orgVol int
if(@tablefetch='ORDER_File')
begin
if(@buySell='1')
begin
set @orgVol=(select isnull(SUM(cast(Original_Volume as int)),0)as OriginalVolume from
ORDER_File where Contract_Code=@contract_code and Buy_Sell_Ind=@buySell)
goto lbllast
end

if(@buySell='2')
begin
set @orgVol=(select isnull(SUM(cast(Original_Volume as int)),0)as OriginalVolume from
ORDER_File where Contract_Code=@contract_code and Buy_Sell_Ind=@buySell)
goto lbllast
end
end


if(@tablefetch='Trade_file')
begin
if(@buySell='1')
begin
set @orgVol=(select isnull(SUM(cast(Trade_Qty as int)),0)as TradeVolume from
Trade_file where Contract_Code=@contract_code and Buy_Sell_Ind=@buySell)
goto lbllast
end

if(@buySell='2')
begin
set @orgVol=(select isnull(SUM(cast(Trade_Qty as int)),0)as TradeVolume from
Trade_file where Contract_Code=@contract_code and Buy_Sell_Ind=@buySell)
goto lbllast
end
end


lbllast:
begin
insert into @resultTable values(@orgVol)
return
end
end

Create Trigger after insert into table in SQL Server 2008

/****** Example of trigger on table after insert ******/

CEATE TRIGGER [dbo].[MarginVal]
   ON   [dbo].[Trade_file]
   AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON ADDED TO PREVENT EXTRA RESULT SETS FROM
-- INTERFERING WITH SELECT STATEMENTS.
SET NOCOUNT ON;
DECLARE @SYSMBOL VARCHAR(200)
DECLARE @EXPIRY VARCHAR(200)
DECLARE @TRADENO VARCHAR(200)
DECLARE @BUYSELL VARCHAR(10)
DECLARE @PRICE DECIMAL(18,2)
DECLARE @LOT VARCHAR(18)
DECLARE @USERID VARCHAR(200)
declare @Trade_Number varchar(200)
------------------------------------------LAST INSETED DATA
SELECT @Trade_Number=Trade_Number,@USERID=USER_ID,@SYSMBOL=CONTRACT_DESCRIPTION,@EXPIRY=EXPIRY_DATE,@TRADENO=TRADE_NUMBER,@BUYSELL=BUY_SELL_IND,@PRICE=PRICE,@LOT=TRADE_QTY FROM INSERTED
-------------------------------------------------------------
------------------------------------ MARGIN FILE  FIND DAILY MARGIN
DECLARE @TMARGIN VARCHAR(200)
SELECT @TMARGIN=TOTALMARGIN FROM MARGIN_FILE WHERE SYMBOL=@SYSMBOL AND CONVERT(DATE,EXPIRY,107)=CONVERT(DATE,@EXPIRY,107)
------------------------------------------------------------------------
------------------------------------FIND LOT SIZE ACCORING TO SYSBMOL AND EXP
DECLARE @PRICEQTN VARCHAR(50)
DECLARE @LOTSIZE NUMERIC(18,2)
SELECT @PRICEQTN=PRICEQTN, @LOTSIZE=LOTSIZE FROM COMMLOTSIZE WHERE COMMODITY=@SYSMBOL

-------------------------------------------------------------------------------SELECT DATA AFTER THEN INSERT IN TO MARGIN TABEL
INSERT INTO CAL_MARGIN (USER_ID, Trade_Number,COMMODITY, EXPIRY, LTP, PRICEQTN, LOTSIZE, MARGIN, LOTVALUE, APPXMARGIN)
SELECT @USERID AS USERID,@Trade_Number,@SYSMBOL AS SYMBOL,@EXPIRY AS EXPIRY,@PRICE AS LTP,@PRICEQTN AS PRICEQTN,@LOTSIZE AS LOTSIZE,@TMARGIN AS MARGIN,
CONVERT(NUMERIC(18,2),@PRICE*@LOTSIZE) AS  LOTVALUE, CONVERT(NUMERIC(18,2),@PRICE*@LOTSIZE*@TMARGIN*CONVERT(INT,RTRIM(@LOT))/100) AS APPX_MARGIN

--SELECT * FROM TRADE_FILE
   
END

Friday, 28 June 2013

Query to Get Records of last n days from table in Sql Server 2008

Try this Sql Query to get all the record of yesterday.......or last 15 days record or last n days records......

"select * from tablename WHERE CONVERT(VARCHAR(10),colname, 112)>= CONVERT(VARCHAR(10),DATEADD(DAY,-(n-1),GETDATE()), 112)"

Query to remove last comma/character in column update in sql server

Try this sql query to update data of column as remove last comma from column value..........

" UPDATE tablename
SET colname= LEFT(colname, len(colname) -1)
WHERE RIGHT(colname,1) = ',' "

Friday, 10 May 2013

Upload Multiple Files with One Fileupload Control and Save these file in database as new row



.aspx Page Content

<style type="text/css">
        #divFile p { font:13px Century }
        #divFile h3 { font:16px Century; font-weight:bold; }
    </style>
    <script type="text/javascript">
    $('#btUpload').click(function() { if (fileUpload.value.length == 0) { alert('No files selected.'); return false; } });
</script>
<div id="divFile" style="width: 95%;float:right; text-align:center">
<b>Upload Multiple Reports by selecting multiple reports files</b>
            <p><asp:FileUpload ID="fileUpload" multiple="true" runat="server" /></p>
            <p><input type="button" id="btUpload" value="Upload Reports"
                onserverclick="btUpload_Click" runat="server" /></p>
            <p><asp:label id="lblFileList" runat="server"></asp:label></p>
            <p><asp:Label ID="lblUploadStatus" runat="server"></asp:Label></p>
            <p><asp:Label ID="lblFailedStatus" runat="server"></asp:Label></p>
            <br />
            </div>



.cs Page Content


protected void btUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile) // CHECK IF ANY FILE HAS BEEN SELECTED.
            {
                int iUploadedCnt = 0;
                int iFailedCnt = 0;
                HttpFileCollection hfc = Request.Files;

                lblFileList.Text = "Select <b>" + hfc.Count + "</b> file(s)";

                if (hfc.Count <= 40)    // 40 FILES RESTRICTION.
                {
                    for (int i = 0; i <= hfc.Count - 1; i++)
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {
                            if (!File.Exists(Server.MapPath("../Report/") + Path.GetFileName(hpf.FileName)))
                            {
                                DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("../Report/"));
                                string sFileName = Path.GetFileName(hpf.FileName);
                                string sFileExt = Path.GetExtension(hpf.FileName);

                                // CHECK FOR DUPLICATE FILES.
                                FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + ".*");

                                if (objFI.Length > 0)
                                {
                                    // CHECK IF FILE WITH THE SAME NAME EXISTS (IGNORING THE EXTENTIONS).
                                    foreach (FileInfo file in objFI)
                                    {
                                        string sFileName1 = objFI[0].Name;
                                        string sFileExt1 = Path.GetExtension(objFI[0].Name);

                                        if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))
                                        {
                                            iFailedCnt += 1;        // NOT ALLOWING DUPLICATE.
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    // SAVE THE FILE IN A FOLDER.
                                    string pid = "";
                                    string fname = "";
                                    if (Session["HID"].ToString() == "ultrad")
                                    {
                                        pid = hpf.FileName.Substring(0, 5);
                                        fname = hpf.FileName.Substring(5, hpf.FileName.Length - 5);
                                    }
                                    else
                                    {
                                        pid = hpf.FileName.Substring(0, 6);
                                        fname = hpf.FileName.Substring(6, hpf.FileName.Length - 6);
                                    }

                                    string path1 = Server.MapPath("../Report/Hosp/") + Session["HID"].ToString();

                                    if (!Directory.Exists(path1))
                                    {
                                        Directory.CreateDirectory(path1);
                                    }

                                    string path = Server.MapPath("../Report/Hosp/" + Session["HID"].ToString() + "/") + pid;

                                    if (!Directory.Exists(path))
                                    {
                                        Directory.CreateDirectory(path);
                                    }

                                 
                                    hpf.SaveAs(Server.MapPath("../Report/Hosp/" + Session["HID"].ToString() + "/" + pid + "/") + Path.GetFileName(DateTime.Now.ToString("yyyyMMddHHmmss") + " " + hpf.FileName));

                                    du.ExecuteSql("insert into Patient_MR(PatientId,RName,ReportPath,Hospital) values('" + pid + "','" + fname + "','Report/Hosp/" + Session["HID"].ToString() + "/" + pid + "/" + Path.GetFileName(DateTime.Now.ToString("yyyyMMddHHmmss") + " " + hpf.FileName) + "','" + Session["HID"].ToString() + "')");
                                 
                                    iUploadedCnt += 1;
                                }
                            }
                        }
                    }
                    lblUploadStatus.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
                    lblFailedStatus.Text = "<b>" + iFailedCnt + "</b> duplicate file(s) could not be uploaded.";
                    fileUpload.Attributes.Clear();

                }
                else lblUploadStatus.Text = "Max. 40 files allowed.";
            }
            else lblUploadStatus.Text = "No files selected.";
        }