Hàm trả về một số nguyên

Hàm trả về một số nguyên

VD1:
Create function CountAge
(
   @Age int
)
returns int
as
begin
   declare @intAge int
   set @intAge= (select count(abc)
            from Table1
            where abc=@Age)
   return @intAge
end


select dbo.CountAge (12)
print dbo.CountAge (12)  


VD2:
USE [WebjetDW]
GO
/****** Object:  UserDefinedFunction [dbo].[udf_GetNumDaysInMonth]    Script Date: 07/15/2010 19:53:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[udf_GetNumDaysInMonth] ( @myDateTime DATETIME )
RETURNS INT
AS
BEGIN
DECLARE @rtDate INT
SET @rtDate =
CASE WHEN MONTH(@myDateTime)
IN (1, 3, 5, 7, 8, 10, 12) THEN 31
WHEN MONTH(@myDateTime) IN (4, 6, 9, 11) THEN 30
ELSE CASE WHEN (YEAR(@myDateTime) % 4 = 0
AND
YEAR(@myDateTime) % 100 != 0)
OR
(YEAR(@myDateTime) % 400 = 0)
THEN 29
ELSE 28 END
END
RETURN @rtDate
END

Query Xóa tất cả các bảng trong Database

WHILE EXISTS(SELECT [name] FROM sys.tables WHERE [type] = 'U')
BEGIN
DECLARE @table_name varchar(50)
DECLARE table_cursor CURSOR FOR SELECT [name] FROM sys.tables WHERE [type] = 'U'
OPEN table_cursor
FETCH NEXT FROM table_cursor INTO @table_name
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC ('DROP TABLE [' + @table_name + ']')
PRINT 'Dropped Table ' + @table_name
END TRY
BEGIN CATCH END CATCH
FETCH NEXT FROM table_cursor INTO @table_name
END
CLOSE table_cursor
DEALLOCATE table_cursor

END

Sử dụng CASE / CAST trong SQL


1. Sử dụng case


select case when region_3='international' then 1 else 2 end as MM from vw_ttv_mtd
2. Sử dụng hàm Cast

CAST (<chuỗi cần chuyển> AS <Kiểu dữ liệu muốn chuyển thành>[Chiều dài])

có thể sử dụng hàm CONVERT (<Kiểu dữ liệu muốn chuyển thành>[Chiều dài], <Chuỗi cần chuyển> [, Định dạng kiểu mới cần chuyển]) với kết quả tương tự.


Ví dụ:

cast(datepart(yyyy, getdate()) as int)select floor(cast(datepart(yyyy, getdate()) as int))