Upload
ashishsharan7444
View
212
Download
0
Embed Size (px)
Citation preview
System Functions1. String functionsa. substringb. rightc. upperd. lowere. charindex f. patindex g. ascii h. chari. ltrim j. rtrim k. spacel. str m. soundex n. replicate2. Date convert functionsEg : select convert(varchar(8),pubdate,2) from titles where title_id = 'MC3026a. 2yy.mm.dd b. 3dd/mm/yy c. 4dd.mm.yy d. 5dd-mm-yy e. 102yyyy.mm.dd f. 103dd/mm/yyyy g. 104dd.mm.yyyy h. 105dd-mm-yyyy 3. Date functionsa. datename b. datepart c. dateadd d. datediff 4. Maths functionsa. absb. ceilingc. floord. rounde. expf. randg. logh. pii. powerj. sqrt k. sinl. cos m. tan5. ISNULL6. COALESCE
User defined Functions
1. User-Defined FunctionEG : CREATE FUNCTION whichContinent (@Country nvarchar(15))RETURNS varchar(30)ASBEGINdeclare @Return varchar(30)select @return = case @Countrywhen 'Argentina' then 'South America'when 'Belgium' then 'Europe'when 'Brazil' then 'South America'when 'Canada' then 'North America'when 'Denmark' then 'Europe'when 'Finland' then 'Europe'when 'France' then 'Europe'else 'Unknown'end
return @returnend
--/// you can use the functions inside the column name
print dbo.WhichContinent('USA')
select dbo.WhichContinent(Customers.Country), customers.* from customers
create table test(Country varchar(15),Continent as (dbo.WhichContinent(Country)))
insert into test (country) values ('USA')
select * from test
2. Inline Table-Value
CREATE FUNCTION CustomersByContinent (@Continent varchar(30))RETURNS TABLE ASRETURN SELECT dbo.WhichContinent(Customers.Country) as continent, customers.* FROM customers WHERE dbo.WhichContinent(Customers.Country) = @ContinentGO
SELECT * from CustomersbyContinent('North America')SELECT * from CustomersByContinent('South America')SELECT * from customersbyContinent('Unknown')
3. Multi-statement Table-Value
CREATE FUNCTION dbo.customersbycountry ( @Country varchar(15) )RETURNS @CustomersbyCountryTab table ([CustomerID] [nchar] (5), [CompanyName] [nvarchar] (40), [ContactName] [nvarchar] (30), [ContactTitle] [nvarchar] (30), [Address] [nvarchar] (60), [City] [nvarchar] (15),[PostalCode] [nvarchar] (10), [Country] [nvarchar] (15), [Phone] [nvarchar] (24), [Fax] [nvarchar] (24))ASBEGININSERT INTO @CustomersByCountryTab SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [PostalCode], [Country], [Phone], [Fax] FROM [Northwind].[dbo].[Customers]WHERE country = @CountryDECLARE @cnt INTSELECT @cnt = COUNT(*) FROM @customersbyCountryTabIF @cnt = 0INSERT INTO @CustomersByCountryTab ([CustomerID],[CompanyName],[ContactName],[ContactTitle],[Address],[City],[PostalCode],[Country], [Phone],[Fax] )VALUES ('','No Companies Found','','','','','','','','')RETURNENDGOSELECT * FROM dbo.customersbycountry('USA')SELECT * FROM dbo.customersbycountry('CANADA')SELECT * FROM dbo.customersbycountry('ADF')