4. 流程控制语句 ① 判断Employees表中是否存在编号为111006的员工,如果存在,则显示该员工的信息,
如果无此人,则显示“查无此人”
IF EXISTS(SELECT Name FROM Employees WHERE EmployeeID='111006') SELECT*FROM Employees WHERE EmployeeID='111006' ELSE
SELECT'查无此人'
② 假设变量X的初始值为0,每次加一,直至X变成5 DECLARE @X INT SET @X=1 WHILE @X<5 BEGIN
SET @X=@X+1
PRINT'X='+CONVERT(char(1),@X) END GO
③ 使用CASE语句对Employees表按部门进行分类
USE YGGL GO
SELECT EmployeeID,Name Address,DepartmentID= CASE DepartmentID WHEN 1 THEN '财务部' WHEN 2 THEN '人力资源部' WHEN 3 THEN '经理办公室' WHEN 4 THEN '研发部' WHEN 5 THEN '市场部' END
FROM Employees
5,.自定义函数的使用
①定义一个函数实现如下功能:对于一个给定的DepartmentID值,查询该值在Departments表中是否存在,若存在则返回0,否则返回-1
CREATE FUNCTION CHECK_ID(@departmentid char(3)) RETURNS integer AS BEGIN
DECLARE @num int
IF EXISTS(SELECT departmentID FROM departments WHERE @departmentid=departmentID) SELECT @num=0 ELSE
SELECT @num=-1 RETURN @num END GO
③ 写一段T-SQL程序调用上述函数。当向Employees表插入一行记录时,首先调用函数
CHECK-ID检索该记录的的DepartmentID值在表Departmengts和DepartmentID字段中是否存在对应的值,若存在,则将该记录插入Employees表
USE YGGL GO
DECLARE @num int
SELECT @num=dbo.CHECK_ID('2') IF @num=0
INSERT Employees
VALUES('990210','张英','本科','1982-03-24',0,4,'南京市镇江路号','8497534','2') GO