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

Monday, 11 September 2017

SQL Transaction In C#,ASP.Net

 Transaction In C#,ASP.Net


SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try
{
for (int i = 0; i < dtTemp.Rows.Count; i++)
{
SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}

catch (Exception Error)
{


}




In above Part the only thing you have to care about is 


SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try
{
  SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
  cmd.ExecuteNonQuery();
  transaction.Commit(); //whenever you call commit it means now finaly
                        //all execution will take place else rollback to catch
}
catch
{
 transaction.Rollback(); 
}

Sunday, 10 February 2013

Working With DateTime In SQL and C#

Date Time Format In C# and SQL







In ASP.net C#

compare two date like TextBoxToDate and TextBoxToDate

DateTime org = DateTime.ParseExact(TextBoxToDate .Text,"dd/MM/yyyy",null);
DateTime enter = DateTime.ParseExact(TextBoxToDate.Text, "dd/MM/yyyy", null);

if(enter.Date<org.Date)
        {
//do what you wish          
        }


       

Thursday, 10 May 2012

Date Diffrence in SQL

Diffrence Between Dates In SQL

We use  convert(varchar, getdate(), 101) format to save data.which will save record in format mm/dd/yyyy  so that we can work on dates easily


On Insertion
Insert into tbSample values ('anycontent',convert(varchar, @OnDate, 101))




On Execution Time
SELECT    * from tbSample where OnDate between convert(varchar, '5/9/2012', 101) and convert(varchar, '5/11/2012', 101)";




Other DateTime Formats Are Below

SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)

                                        -- Oct  2 2008 11:01AM         

SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008                 

SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd -- 2008.10.02          

SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy

SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy

SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy

SELECT convert(varchar, getdate(), 106) -- dd mon yyyy

SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy

SELECT convert(varchar, getdate(), 108) -- hh:mm:ss

SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)

                                        -- Oct  2 2008 11:02:44:013AM  

SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy

SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd

SELECT convert(varchar, getdate(), 112) -- yyyymmdd

SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm

                                        -- 02 Oct 2008 11:02:07:577    

SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)

SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)

SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm

SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm

                                        -- 2008-10-02T10:52:47.513

-- SQL create different date styles with t-sql string functions



SELECT convert(varchar(7), getdate(), 126)                 -- yyyy-mm

SELECT right(convert(varchar, getdate(), 106), 8)

Monday, 9 January 2012

Delete All Tables,Views,Functions or Stored Procedure In SQL



Delete All Tables,Views,Functions or Stored Procedure In SQL


Some time you require to modify your database,but you don't know either they are tables,Views,functions or stored procedure.and you just want to run Delete all command for particular database objects.So You Can Use Curser To Execute The Requirement !



Delete All Tables

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql
'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON 
tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

Delete All Stored Procedures

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'p'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
            if @procName <> 'DeleteAllProcedures'
                  exec('drop procedure ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

Delete All Views


declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'v'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop view ' + @procName)
                  fetch next from cur into @procName
      end
close cur
deallocate cur

Delete All Functions


declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'fn'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop function ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

But What if you want just table entries should be truncate 
follow this its works fine with SQL server R2

EXEC sp_MSForEachTable "TRUNCATE TABLE ?"

Wednesday, 28 December 2011

SQL SERVER DO and DO NOT

 Basic SQL Query with many filters

Sometimes you have so much of data and you require to filter the data with few twist then you can implement this query that will simply check
TWO conditions between
TWO coloumns of
TWO Tables


take a look and you'll get explained better
------------------------------------------------------------------------------------------------------------
SELECT     Author_no
FROM         Author
WHERE     
(confirmation = 1) and Author_no  not in(SELECT distinct Author_nox FROM SecondAuthortable)
-------------------------------------------------------------------------------------------------------------
where Author_nox & Author_no,confirmation are three columns of two diffrent tables.
SecondAuthortable and Author simultaneously.

Converting Number Into Words By User Defined Function in SQL Server

Converting Number Into Words Function In SQL Server

Some time you  require to make things happen automatically in sql server,and when the word automatically comes in front of a programmer it means a function who can do it!So Lets Create A Function In SQL Who Can Do All These


Below In Just Two Steps You Will Create A Function in SQL Who Can Convert Your Numeric Value In Words.

1)Create Function,then Execute It!

___________________________________________________________________________________

CREATE FUNCTION dbo.udf_Num_ToWords (

 @Number Numeric (38, 0) -- Input number with as many as 18 digits

) RETURNS VARCHAR(8000) 
/*
* Converts a integer number as large as 34 digits into the 
* equivalent words.  The first letter is capitalized.
*
* Attribution: Based on NumberToWords by Srinivas Sampath
*        as revised by Nick Barclay
*
* Example:
select dbo.udf_Num_ToWords (1234567890) + CHAR(10)
      +  dbo.udf_Num_ToWords (0) + CHAR(10)
      +  dbo.udf_Num_ToWords (123) + CHAR(10)
select dbo.udf_Num_ToWords(76543210987654321098765432109876543210)
 
DECLARE @i numeric (38,0)
SET @i = 0
WHILE @I <= 1000 BEGIN 
    PRINT convert (char(5), @i)  
            + convert(varchar(255), dbo.udf_Num_ToWords(@i)) 
    SET @I  = @i + 1 
END
*
* Published as the T-SQL UDF of the Week Vol 2 #9 2/17/03
****************************************************************/
AS BEGIN

DECLARE @inputNumber VARCHAR(38)
DECLARE @NumbersTable TABLE (number CHAR(2), word VARCHAR(10))
DECLARE @outputString VARCHAR(8000)
DECLARE @length INT
DECLARE @counter INT
DECLARE @loops INT
DECLARE @position INT
DECLARE @chunk CHAR(3) -- for chunks of 3 numbers
DECLARE @tensones CHAR(2)
DECLARE @hundreds CHAR(1)
DECLARE @tens CHAR(1)
DECLARE @ones CHAR(1)

IF @Number = 0 Return 'Zero'

-- initialize the variables
SELECT @inputNumber = CONVERT(varchar(38), @Number)
     , @outputString = ''
     , @counter = 1
SELECT @length   = LEN(@inputNumber)
     , @position = LEN(@inputNumber) - 2
     , @loops    = LEN(@inputNumber)/3

-- make sure there is an extra loop added for the remaining numbers
IF LEN(@inputNumber) % 3 <> 0 SET @loops = @loops + 1

-- insert data for the numbers and words
INSERT INTO @NumbersTable   SELECT '00', ''
    UNION ALL SELECT '01', 'one'      UNION ALL SELECT '02', 'two'
    UNION ALL SELECT '03', 'three'    UNION ALL SELECT '04', 'four'
    UNION ALL SELECT '05', 'five'     UNION ALL SELECT '06', 'six'
    UNION ALL SELECT '07', 'seven'    UNION ALL SELECT '08', 'eight'
    UNION ALL SELECT '09', 'nine'     UNION ALL SELECT '10', 'ten'
    UNION ALL SELECT '11', 'eleven'   UNION ALL SELECT '12', 'twelve'
    UNION ALL SELECT '13', 'thirteen' UNION ALL SELECT '14', 'fourteen'
    UNION ALL SELECT '15', 'fifteen'  UNION ALL SELECT '16', 'sixteen'
    UNION ALL SELECT '17', 'seventeen' UNION ALL SELECT '18', 'eighteen'
    UNION ALL SELECT '19', 'nineteen' UNION ALL SELECT '20', 'twenty'
    UNION ALL SELECT '30', 'thirty'   UNION ALL SELECT '40', 'forty'
    UNION ALL SELECT '50', 'fifty'    UNION ALL SELECT '60', 'sixty'
    UNION ALL SELECT '70', 'seventy'  UNION ALL SELECT '80', 'eighty'
    UNION ALL SELECT '90', 'ninety'   

WHILE @counter <= @loops BEGIN

 -- get chunks of 3 numbers at a time, padded with leading zeros
 SET @chunk = RIGHT('000' + SUBSTRING(@inputNumber, @position, 3), 3)

 IF @chunk <> '000' BEGIN
  SELECT @tensones = SUBSTRING(@chunk, 2, 2)
       , @hundreds = SUBSTRING(@chunk, 1, 1)
       , @tens = SUBSTRING(@chunk, 2, 1)
       , @ones = SUBSTRING(@chunk, 3, 1)

  -- If twenty or less, use the word directly from @NumbersTable
  IF CONVERT(INT, @tensones) <= 20 OR @Ones='0' BEGIN
   SET @outputString = (SELECT word 
                                      FROM @NumbersTable 
                                      WHERE @tensones = number)
                   + CASE @counter WHEN 1 THEN '' -- No name
                       WHEN 2 THEN ' thousand ' WHEN 3 THEN ' million '
                       WHEN 4 THEN ' billion '  WHEN 5 THEN ' trillion '
                       WHEN 6 THEN ' quadrillion ' WHEN 7 THEN ' quintillion '
                       WHEN 8 THEN ' sextillion '  WHEN 9 THEN ' septillion '
                       WHEN 10 THEN ' octillion '  WHEN 11 THEN ' nonillion '
                       WHEN 12 THEN ' decillion '  WHEN 13 THEN ' undecillion '
                       ELSE '' END
                               + @outputString
      END
   ELSE BEGIN -- break down the ones and the tens separately

             SET @outputString = ' ' 
                            + (SELECT word 
                                    FROM @NumbersTable 
                                    WHERE @tens + '0' = number)
              + '-'
                             + (SELECT word 
                                    FROM @NumbersTable 
                                    WHERE '0'+ @ones = number)
                   + CASE @counter WHEN 1 THEN '' -- No name
                       WHEN 2 THEN ' thousand ' WHEN 3 THEN ' million '
                       WHEN 4 THEN ' billion '  WHEN 5 THEN ' trillion '
                       WHEN 6 THEN ' quadrillion ' WHEN 7 THEN ' quintillion '
                       WHEN 8 THEN ' sextillion '  WHEN 9 THEN ' septillion '
                       WHEN 10 THEN ' octillion '  WHEN 11 THEN ' nonillion '
                       WHEN 12 THEN ' decillion '   WHEN 13 THEN ' undecillion '
                       ELSE '' END
                            + @outputString
  END

  -- now get the hundreds
  IF @hundreds <> '0' BEGIN
   SET @outputString  = (SELECT word 
                                      FROM @NumbersTable 
                                      WHERE '0' + @hundreds = number)
                 + ' hundred ' 
                                + @outputString
  END
 END

 SELECT @counter = @counter + 1
      , @position = @position - 3

END

-- Remove any double spaces
SET @outputString = LTRIM(RTRIM(REPLACE(@outputString, '  ', ' ')))
SET @outputstring = UPPER(LEFT(@outputstring, 1)) + SUBSTRING(@outputstring, 2, 8000)


RETURN @outputString -- return the result
END
 
____________________________________________________________________________________ 



2)Use Function




here dbo.udf_Num_ToWords is name of function.
tbl_picalculate is table name
Amount is  a Coloumn name or for testing purpose you can simply type any value like 122 and execute the query.

So Concluding All,things become like this
i: select dbo.udf_Num_ToWords(122) from tbl_picalculate

ii: select dbo.udf_Num_ToWords(Amount) from tbl_picalculate


moreover....
Now The Very Basic Query of SQL 

           select username,amount from TABLE
becomes
            select username,dbo.udf_Num_ToWords(amount from) TABLE


and further you better know where to implement it!




Saturday, 10 December 2011

Transaction in SQL

SQL Transaction In C#                                                                                                        





SQL Transaction In C# means either run all command or do nothing (ROLLBACK)
to know the transaction process bit briefly lets take an example.

SqlTransaction trans;                       //globaly declared


try
{
cmd1=new sql(________);
int i=cmd.ExecuteNonQuery();



cmd2=new sql(________)
int j=cmd.ExecuteNonQuery()


trans.Commit();
if((i>0 ) && (j>0))
{
"record inserted"
}
catch(Exception)
{
trans.Rollback();
"Record not insered";
}
con.close();



Friday, 9 December 2011

saving changes is not permitted.the changes you have made require the following tables to be dropped and re-created

Mainly the cause behind this is ,SQL prevent saving changes that require table re-creation


If I am not wrong do you guys facing this kind of pop up while saving a table,which you have build already.
below pop up shows that you can not update the design of table, usually this function work in bulk Professions,where Project head need the developer to do test on his table without modifying anything from database.
















ok after this,lets come to the point.
just follow the below procedure...
which means go on TOOLS then OPTIONS.
(Note:before proceeding please close all opened window under sql window)




Add caption












After which you'll get this kind of screen of OPTIONS(below image),now click on Designer on left hand side of window,then table and definition designers...
in which you just have to UNCHECKED a option which is

  • prevent saving changes that require table re-creation.
    (like below image!)

that all! you done it ,and now can modify your table whenever you require.






Sunday, 6 November 2011

Common SQL Solutions



1)insert one table into other directly in sql

insert into tbl_Processing (Process_ID,ArrivalId,Adate,BoxDesignId,Qty,Rate,Total) SELECT   Process_ID,ArrivalId,Adate,BoxDesign,Qty,Rate,TotalBoxAmount FROM  temp_BoxProcessing


2)UNION two table
select * from(select * from TrainingSessionSummerTrainView  union select * from TrainingSessionIndusView )a where orgfu_org_name=1

3) Versions error
Unfortunatly it is due to old version of sql eg.2000

 and you are trying to implement something which was not available on that time...
leave it whatever it was the solution is
just replace [dbo] from your table even [ ] these brackets from your table name
(its a solution for one of its kind,you may have other prob.,let me know if any)


ask me if any further question you have...

4)Date differences in SQL


SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(getDate())-1),getDate()),101)



5)Create New Table (A CLONE COPY OF EXISTING TABLE)

SELECT   * 
INTO           New_Table
FROM         Exisiting_Table

6)What to Show When There Is NO Value returning in row?

suppose the query is ...

select price from tableproduct where id='123'


and there is no id with 123
then you will get a single row in result with NULL

but you further need some calculation with this output so just make NULL to 0 by this query...

select MAX(isnull(pattern,0)) from tbl_rueno where pi_no='1111'

 but be careful if the data type of the selected field is non int,
you should make column data type any datatype to int,so we did bit modification below to do so...


MAX(isnull(convert(int,crate_to),0))+1 from tbl_rueno where pi_no='1111'






Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...