SQL 在IBM DB2中选择随机行

SELECT column, RAND() as IDX  
FROM table  
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

SQL 从Oracle中选择随机行

SELECT column FROM  
( SELECT column FROM table  
ORDER BY dbms_random.value )  
WHERE rownum = 1

SQL 在datetime中将时间设置为0

select cast( floor( cast( getdate() as float ) ) as datetime ) as date_only

SQL 从SQL数据库中选择随机行。

SELECT * FROM `table` ORDER BY rand() LIMIT 1

SQL 查找重复行

-- Select Duplicates
SELECT		[column], COUNT([column]) AS NumOccurrences
FROM		[TABLENAME]
GROUP BY	[column]
HAVING		( COUNT([column]) > 1 )

SQL 生成插入语句

/* 
  SQL Server Row Script Creator

  This script will generate script to insert/update from a source table in one database to an 
  identical destination table in another database or server.  It can be run for inserts or updates,
  and can be run for a single row in insert and update mode, or all rows in a table for insert mode.
*/

declare @tab varchar(50)
       ,@pk1Val varChar(10)
	   ,@pk1Name varChar(50)
	   ,@qt char(1)
	   ,@StatementType varChar(10)
set nocount on
/*
 Instructions:
 1) open script and connect to the source database
 2) Change the  variable values to change the output options for the script below (@tab, @statementtype etc)
 3) execute the script (best to use text output)
 4) copy the script output into a script window, and run on the destination table.

@Tab = the name of the source table
@pk1Val = if selecting a single row or doing an update statement, the value of the primary key for that row
@pk1Name = if inserting a single row or doing an update statement, the name of the column for the primary key
@StatementType = either 'INSERT' to create an insert statement or 'UPDATE' for an Update statement
*/
select @tab = 'Access_Right_Role', @pk1Val = '', @pk1Name = '', @StatementType = 'INSERT'

declare @tabName varchar(50)
      , @colName varchar(50)
      , @colType varchar(50) 
      , @collength varChar(50)
	  , @colOrder int
	  , @IsIdent char(1)
	

create table #output (Line varChar(4000), LineOrder int, rowNumber int)
create table #ColumnValues (ColName varChar(250), ColOrder int, RowNumber int, ColValue varchar(4000), colType varchar(50))

declare @out varchar(4000)
       ,@lineCounter int
	   ,@ColValue varchar(4000)
	   ,@sortCol varchar(50)


/* get the ordering column */
select @sortCol = sc.Name
from sysobjects so
inner join syscolumns sc
on so.id=  sc.id
inner join systypes st
on sc.xtype = st.xusertype 
where so.Name = @tab
 and ((sc.status = 0x80) OR (ColOrder = 1 and not sc.status = 0x80 ))



/* put in the repeating values based on the columns*/
declare objCurs CURSOR FOR 
select so.name, sc.name, st.name, sc.length, Case when sc.status = 0x80 then 'Y' else 'N' END as IsIdent, ColOrder
from sysobjects so
inner join syscolumns sc
on so.id=  sc.id
inner join systypes st
on sc.xtype = st.xusertype
where so.Name = @tab

DECLARE @counter int, @numCols int, @RowNumber int, @LastRowNumber int, @maxRowNumber int, @maxColOrder int

select @numCols = count(sc.id) 
from sysobjects so
inner join syscolumns sc
on so.id=  sc.id
where so.Name = @tab

--select @numCols  --debug code

open objCurs
Fetch from objCurs
into @tabname, @colName, @colType, @colLength, @isIdent, @colOrder

while @@fetch_status = 0
begin
	SET @counter = 0
	/* get the value from the table */
	if @IsIdent = 'N'
	BEGIN
	--select @TabName,@ColName, @ColType, @ColLEngth, @isIdent, @ColOrder  --debug code
		/* increase better type handling by inserting more case statments, handling different data types */
		if datalength(@pk1Name) = 0 or datalength(@pk1Val) = 0
		begin
			/* getting all rows in the table */
			exec ('insert into #ColumnValues (ColName, ColOrder, ColValue, ColType) 
					select  ''' + @colName + ''', ' + @ColOrder + ', Convert(nvarchar(4000),' + @colName + ') , ''' + @colType + ''' from ' + @tabName + ' order by ' + @SortCol + ' ' +
				  ' declare @counter int set @counter = 0 ' +
				  ' update #ColumnValues Set @Counter = RowNumber = @Counter + (' + @numCols + ' * 10) where ColName = ''' + @colName + '''' )
		end
		else
		begin
			/* filtering by a pk val */
			exec ('insert into #ColumnValues (RowNumber, ColName, ColORder, ColValue, ColType)
					select 0, ''' + @colName + ''', ' + @ColOrder + ', Convert(nvarchar(4000),' + @colName + ') , ''' + @colType + ''' from ' + @tabName + 
				  ' where ' + @pk1Name + ' = ' + @pk1Val) 
		end 


	end /* if @isIdent = 'n' */

	Fetch Next from objCurs
	into @tabname, @colName, @colType, @colLength, @IsIdent, @ColOrder
end 

--select * from #ColumnValues --debug code
select @MaxRowNumber = Max(rowNumber) from #columnValues --keep highest row number so we know when we are finished
select @MaxColOrder = max(ColOrder) from #ColumnValues where RowNumber = @MaxRowNumber

/* next cursor for outputting the results from the retval table into the output table */
declare ColVal_Curs  cursor for
select ColName , ColOrder , RowNumber , ColValue , colType 
from #ColumnValues
order by RowNumber, ColOrder

open ColVal_Curs

--set the last row number to the first in the table, so post loop checking works
select @lastRowNumber = min(rowNumber) from #ColumnValues 
set @lineCounter = @LastRowNumber --initialise at the first row

fetch from ColVal_Curs into
@colName, @ColOrder, @RowNumber, @colValue, @ColType

while @@Fetch_status = 0
BEGIN /* cursor loop */

		/* get the quote type to enclose the value from the column type */
		select @qt = case @colType
					 when 'nvarchar' then ''''
					 when 'nchar' then ''''
					 when 'DateTime' then ''''
					 when 'ntext' then ''''
					 when 'varchar' then ''''
					 when 'char' then ''''
					 when 'text' then ''''
					 else ''  
					 end 
		
		
--select @linecounter, @colName, @ColOrder, @RowNumber, @colValue, @ColType
		if not @ColValue is null 

		if @rowNumber = @lineCounter
			select @out = case @statementType
							when  'UPDATE' THEN 'Update ' + @tab + ' SET '
							when  'INSERT' then 'INSERT INTO ' + @tab + ' ('
						  end 
		begin
			if @StatementType = 'UPDATE' 
			BEGIN 
				select @Out = @out + @colName + ' = ' + @qt + COALESCE(@ColValue, 'NULL') + @qt + ',' -- + @ColType 
				insert into #output (Line, LineOrder)
				values (@out, @lineCounter)
			end 
			if @statementType = 'INSERT' 
			BEGIN 
				/* put comma in */
				if @lineCounter > @RowNumber --not first line in set of values for row
					select @out = @out + ','
				
				/*put in the name of the column */
				insert into #output (Line, LineOrder)
				values (@out + @colName
					  , @lineCounter)

				if @lineCounter > @RowNumber --not first line in set of values for row 
					select @out = ','
				else
					select @out = ''
				/* put in the value of the column */
				insert into #output (Line, LineOrder)
				values (@out + @qt + COALESCE(@ColValue, 'NULL') + @qt 
					  , @lineCounter + 10 + @numCols)
			
			END 
		end  /*not @ColValue is null */
	select @lineCounter = @lineCounter + 1
	set @out = ''
/* get the next record*/
	fetch from ColVal_Curs into
	@colName, @ColOrder, @RowNumber, @colValue, @ColType
--select @ColOrder, @MaxColOrder, @@Fetch_Status  --debug code
	if (@rowNumber > @lastRowNumber) or (@RowNumber = @MaxRowNumber and @MaxColOrder = @ColOrder and @@FEtch_Status = -1)
	BEGIN
	/* this bit of processing is done whenever the set of columsn in a row changes to the next row of the original table*/
	/* ie we are building a record to insert, and the PK changes because we are at the next record */
		/* remove the last comma from the last line */
		declare @lastLine int

		if @statementType = 'UPDATE'
		begin
			/*remove last comma*/
			update #output
			set Line = left(Line,datalength(Line)-1)
			where lineOrder = @LineCounter

			/* insert a 'where' clause */

			insert into #output (line, LineOrder)
			select ' WHERE ' + @pk1Name + ' = ' + @pk1Val, Max(LineOrder) + 1 from #output

		end
		if @statementType = 'INSERT'
		BEGIN
			/* put in a 'values' statement between the column names and the column values */
			insert into #output (Line, LineOrder)
			values (') VALUES (', @LastRowNumber + @numCols + 5)
			/* close off the lot */
			insert into #output (line, lineorder)
			select ')', Max(LineOrder) + 1 from #output
		END 
		set @lastRowNumber = @RowNumber
		set @lineCounter = @RowNumber  /* reset linecounter for next set */
		update #output
		set RowNumber = @rowNumber
		where RowNumber is null
	End /* if rownumber > last row number */

end /* cursor loop */

close objCurs
deallocate objCurs

close ColVal_Curs
deallocate ColVal_Curs


/* the following is an extra loop over the original code to output the code as one statement per row */
create table #combineOutput (rowNumber int, line varchar(4000))
/* get the statements out from the list*/
declare @output varchar(8000), @codeLine varchar(4000), @thisRowNum int, @lastRowNum int
select @output = ''
declare line_curs cursor for 
select line, RowNumber  from #output order by RowNumber, lineorder

open line_curs
fetch from line_curs into @codeLine, @thisRowNum
select @lastRowNum = @thisRowNum
while @@fetch_status = 0
begin
	if @thisROwNum > @lastRowNum
	BEGIN
		/* insert a row into the aggregate table if a new row number */
		insert into #combineOutput (rowNumber, line) values (@rowNumber, @output)
		set @output = ''
	END 
	select @output = @output + @codeLine + ' '
	select @lastRowNum = @thisRowNum
	fetch from line_curs into @codeLine, @thisRowNum
end
/* the last row needs to be inserted */
insert into #combineOutput (rowNumber, line) values (@rowNumber, @output)

close line_curs
deallocate line_curs

select line as [Copy and paste code from below] from #combineOutput order by rowNumber

/*  bug tracking code - uncomment to diagnose problems
select distinct RowNumber from #ColumnValues order by 1
select * from #ColumnValues
order by RowNumber, ColOrder, ColName, ColValue
*/
drop table #output
drop table #combineOutput
drop table #ColumnValues
set nocount off

SQL 行到列Pivot示例

/****** Object:  StoredProcedure [dbo].[msp_Costing_Data_Select]    Script Date: 01/03/2008 20:09:01 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[msp_Costing_Data_Select]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[msp_Costing_Data_Select]

/****** Object:  StoredProcedure [dbo].[msp_Costing_Data_Select]    Script Date: 01/03/2008 20:09:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[msp_Costing_Data_Select]
	@costingid [int]
AS
	DECLARE @cols		[nvarchar](MAX)
	DECLARE @SQL		[nvarchar](MAX)

	SELECT		@cols = COALESCE(@cols + ',[' + [key] + ']','[' + [key] + ']')
	FROM		[dbo].[Costing_Schema]
	ORDER BY	[position]

	--PRINT @cols

	SET @SQL =	N'SELECT ' + @cols + '
					FROM	( 
								SELECT  cd.[uid]
										,cs.[key]
										,cd.[value]
								FROM    [dbo].[Costing_Schema] AS cs
								JOIN	[dbo].[Costing_Data] As cd 
								ON		cs.[key] = cd.[key] 
								WHERE	cd.[costingid] = ' + CAST(@costingid AS nvarchar) + '
							) p PIVOT	(MAX([value])
										FOR [key] IN (' + @cols + ')
										) AS pvt
							ORDER BY [uid]'
	--PRINT @SQL

	EXEC sp_executesql @SQL
GO

GRANT EXECUTE ON [dbo].[msp_Costing_Data_Select] TO [costingWeb]
GO

SQL 选择DataBase Schema

SELECT TABLE_CATALOG
, TABLE_SCHEMA
, TABLE_NAME
, ORDINAL_POSITION
, COLUMN_NAME
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, COLUMN_DEFAULT
, IS_NULLABLE
, COLLATION_NAME 
FROM 
INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = (N'Sales')
ORDER BY ORDINAL_POSITION

SQL 基本TSQL游标语法

declare @EntityName as varchar(100)

    declare DepNameCursor Cursor FAST_FORWARD 
    FOR select top 100 MailName from DepNameExt

    OPEN DepNameCursor
    FETCH NEXT FROM DepNameCursor
    INTO @EntityName

    WHILE @@Fetch_Status = 0 
    BEGIN 

        INSERT INTO [UDC].[dbo].[Entity]
           ([Name])
        VALUES
           (@EntityName)

        FETCH NEXT FROM DepNameCursor
        INTO @EntityName
    END

    CLOSE DepNameCursor
    DEALLOCATE DepNameCursor

SQL TSQL尝试捕获错误处理

BEGIN TRY
   BEGIN TRANSACTION    -- Start the transaction

   -- Delete the Employee's phone numbers
   DELETE FROM EmployeePhoneNumbers
   WHERE EmployeeID = @EmployeeID

   -- Delete the Employee record
   DELETE FROM Employees
   WHERE EmployeeID = @EmployeeID

   -- If we reach here, success!
   COMMIT
END TRY
BEGIN CATCH
  -- Whoops, there was an error
  IF @@TRANCOUNT > 0
     ROLLBACK

  -- Raise an error with the details of the exception
  DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
  SELECT @ErrMsg = ERROR_MESSAGE(),
         @ErrSeverity = ERROR_SEVERITY()

  RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH