Monday, 19 January 2015

SQL Queries...

  1. 1       Set default value in SQL columns in created table.
    ALTER TABLE [dbo].[tblVisitorRegistation2015] ADD  DEFAULT (getdate()) FOR [entry_date]

    2.  If your Command contains output parameters or return values, they will not be available until the DataReader is closed.

    3.  Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.


    4.      If ExecuteScalar is used to execute select query that retrieves table data. It can return only first row first column cell value. - See more at: http://dbakings.com/ASP/ASPADOInsert.aspx#sthash.uJYt7FrF.dpuf

    5.      Dataset is capable of storing more than one table.
    Dataset is used to store data on client side. - See more at:
    http://dbakings.com/ASP/ASPADOInsert.aspx#sthash.uJYt7FrF.dpuf

    6.  Rename table or view with query(270914)
    SP_Rename 'Old Name', 'New name'

    7.  Rename column in table with query(270914)
    sp_RENAME 'TableName.[OldColumnName]' , '[NewColumnName]', 'COLUMN'

    8.  use of substring in sql(270914)
    select max(cast(substring(exId,8,4) as smallint)) as maxId from tblExRegInfo where eventid='event221'
    select substring('amod kumar',4,4) o/p: d ku

    9.  find nth highest salary (270914)
    SELECT TOP 1 Salary
    FROM (
          SELECT DISTINCT TOP 3 Salary
          FROM TblSalary
          ORDER BY Salary DESC
          ) AS Emp
    ORDER BY Salary
    Get nth highest salary

    select min(salary) from TblSalary where salary in (select distinct top 3  salary from TblSalary order by salary desc)

    Get nth lowest salary

    select max(salary) from TblSalary where salary in (select distinct top 3  salary from TblSalary order by salary)

    10.find second highest salary(270914)
    select MAX(Salary) from Employee WHERE Salary <> (select MAX(Salary) from Employee )
    Delete Duplicate record from the table
    DELETE SUB FROM
    (SELECT *,ROW_NUMBER() OVER (PARTITION BY ProdID ORDER BY ProdID) cnt
     FROM tblProductMaster where  eventid='event230' and FormId='11') SUB
    WHERE SUB.cnt > 1

    SELECT * FROM dbo.duplicateTest
    DELETE TOP(1) FROM dbo.duplicateTest WHERE ID = 1
    SELECT * FROM dbo.duplicateTest

    Or

    SET ROWCOUNT 1
    DELETE FROM dbo.duplicateTest WHERE ID = 1
    SET ROWCOUNT 0

    11.Get the lenght for any column in sql server
    SELECT @FirstName AS FirstName,DATALENGTH(@FirstName) AS Length

    12.Date format with full month name like "23 march 2014"
    CAST(DAY(Deadline) AS VARCHAR(2)) + ' ' + DATENAME(MONTH, Deadline) + ' ' + CAST(YEAR(Deadline) AS VARCHAR(4)) AS Deadline1

    13.show all tables, databases in your selected databases and also show the description of table.
    select * from sys.tables;
    select * from INFORMATION_SCHEMA.TABLES

    14.Dynamic Query //set column name dynamically in a query
    declare @abc char(20)=''
    set @abc=(select empname from employeeinfo where empid=12)
    exec('select ROW_NUMBER() over (order by empid) as '+@abc+',empname from employeeinfo')

    15.Drop any column from the table
    alter table TblAdminFloorPlanDetails drop column EmailID

    16.Create new table from existing one with all record or copy data form one table to another
    SELECT A.COL1,A.COL2... INTO NEWTABLE FROM EXISTINGTABLE WHERE 1=1
    SELECT A.COL1,A.COL2... INTO NEWTABLE FROM EXISTINGTABLE WHERE 1=0

    17.Add Multiple column in existing time
    alter table tblManualform18
    add UploadVideo nvarchar(max),categories nvarchar(max),content nvarchar(max)

    18.DateFormate output given below if required.
    select CONVERT(VARCHAR(12),GETDATE(),106) as DeadLine  
    o/P:-  18 Nov 2013

    19.Show result order by date after convert that why date time show in asc or desc
    SELECT entry_date FROM tbldownloadBrochureConfWest ORDER BY CONVERT(DateTime, entry_date,101)  asc

    20.Another way to solve this problem but u have to save it in another column in the d/b and have to do oder by that column.
    select convert(varchar(15),CONVERT(DateTime, entry_date,101),112)from tbldownloadBrochureConfWest

    21.show serial number in page with the help of sql server.
    select row_number() over (order by entry_date desc)as [Sr no.]from tbldownloadBrochureConfWest

    22.Create a new table from existion one
    select * into tblfloor from tblfloorplan

    23.Add Auto increment in sql server in premade table.  26_10_13 (270914)
    alter table YourTable add ID int identity(start, increment)

    24.Copy record from existing table to existing table. (270914)
    insert table2 select * from table1
    insert into table2 select name from table1
    insert table2 select name from table1
    INSERT Table2 (columnX, columnY)
    SELECT column1, column2 FROM Table1 WHERE [Conditions]
    25.Show selected content in gridviw for bind 011014
    26.select (left('amodsdfsfsfs sdsf sdfsf sf sdfsdf ',20)+'...') as Content
    27.Concatenate row values
    select link_href + ',' from tbldnlinks where eventid='event250' for xml path('')
    //2nd Method
    declare @ColumnNameList VARCHAR(MAX)
     SELECT @ColumnNameList  = COALESCE(@ColumnNameList +',' ,'') + name FROM t2
    select @ColumnNameList


    28.Resset Identity column and start from our wisth
    DBCC CHECKIDENT('[table_name]', RESEED, [new_reseed_value])
            -- for example
            DBCC CHECKIDENT('T1', RESEED, 2)

    29.Insert value in Identity column
    SET IDENTITY_INSERT T1 ON
    insert into T1(id)values(45)
    SET IDENTITY_INSERT T1 OFF
    30.Insert value in Identity column
    31.insert into T1 default values
    32.Use of table DataType
    DECLARE @ListofIDs TABLE(IDs VARCHAR(100))
    INSERT INTO @ListofIDs VALUES('a'),('10'),('20'),('c'),('30'),('d')
    SELECT IDs FROM @ListofIDs;
    select max(IDs) FROM @ListofIDs;
    33.Differece between replace and Stuff
    STUFF ( character_expression , start , length , replaceWith_expression )

    select stuff('abcd',1,2,'AB')

    select replace('abcd','a','A')

    34.Case statement
    update t3 set desid=case desid when 1 then 0 when 0 then 1 else null end

    35.Self join example
    select em.id, em.designation as employee,mg.designation as manager from t3 as em left join t3 as mg on em.desid=mg.id

    36.  Get employee details from employee table whose first name ends with 'n' and name contains 4 letters

    Select * from EMPLOYEE where FIRST_NAME like '___n' (Underscores)

    Select * from EMPLOYEE where FIRST_NAME like 'J___' (Underscores)

No comments:

Post a Comment