Chinaunix首页 | 论坛 | 博客
  • 博客访问: 55403
  • 博文数量: 16
  • 博客积分: 125
  • 博客等级: 民兵
  • 技术积分: 205
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-04 13:05
文章分类

全部博文(16)

文章存档

2016年(2)

2015年(3)

2013年(6)

2012年(5)

我的朋友

分类: 嵌入式

2012-12-27 14:46:53

前些日子复习基础知识,厚厚的课本懒得再翻看了,在网上咣当,看到几个小例子想着整理了一下,在这里记录一下吧。

1.   用循环产生数字                                    1101,1102,1103,……1105,1106,1118,1201,1202,1203,1204,12051206,1207……1218这是一组。2101,2102,2103,2104,2105……21182201,2202……2218这是第二组,直到第六组:6101,6102,6103……61186201,6202,6203,6204,6205,6206,6228,这个表字段就两个,一个ID,一个存储这个,用循环怎么实现?实现效果如下图:

答:

2.   请看下面这段代码,输出结果是什么?

declare @a int ,@b int ,@c int

select @a = 1,@b = 1

while @a <3

begin

print @a -- 打印变量@a的值

     while @b < 3

     begin

     select @c = 100*@a + @b

     print @c --打印变量@c的值

     select @b = @b + 1

     end

select @a = @a + 1

select @b = 1

end

print @a

print @b

print @c

答案:

注意SQL关键字:waitfor delay waitfor time 的区别,distinct指定检索独有的列值,不重复。

3.   写出SQL语句,求员工信息表中工资最高的员工姓名?注意工资最高的员工可能不止一个

select * from dbo.T_UserInfo where Type = (select Max(Type) from dbo.T_UserInfo)

4.   如何把多个参数传递到存储过程,并使存储过程依次读取参数执行相应的更新操作?(例如,表Exhibitions 中有展品的ID,前台选中多个展品,需要更新选中展品的状态,如何把选中展品的ID传到存储过程中,然后在存储过程中根据传过来的ID更新相应展品的状态)

SQL Server 2005及以下版本不支持创建表值参数,

如何把表格变量传递到存储过程?(参考百度文库)

--创建表格

if object_id ('T_SalesHistory')>0

drop table T_SalesHistory;

go

 

create table T_SalesHistory

(

SaleID int identity(1,1) not null primary key,

Product varchar(10) null,

SaleDate datetime null,

SalePrice money  null

)

go

--建立表值参数,这样可以在数据库引擎里定义表格结构,让你可以在需要的时候在过程代码里使用该表格

create type T_SalesHistoryTableType

as table

(

Product varchar(10) null,

SaleDate datetime null,

SalePrice money null

)

--如果想要查看系统中其它类型的表格类型定义,可以执行下面这个查询命令,查看系统命令

select * from sys.table_types

 

--定义用来处理表值参数的存储过程,

create procedure usp_InsertBigScreenProcedures(@TableVariable T_SalersHistoryTableType readonly)

as

begin

insert into T_SalesHistory(Product,SaleDate,SalePrice) select Product,SaleDate,SalePrice from @TableVariable where Product = 'BigScreen'

end

go

5.   存储过程中游标的使用方法?

create procedure updateState

as

begin

--fc 游标的名字

declare fc cursor for select ID from dbo.T_UserInfo where Type = 4

declare @a int --定义变量存储取到的值

open fc  --开启游标

while @@fetch_status = 0 --取值

begin

fetch next from fc into @a --将从游标中的到的值传给变量,游标下移

--需要执行的操作,例如对表中字段的更新

update dbo.T_UserInfo set State = 0 where ID=@a

update dbo.T_UserInfo set LoginName = 'abc' where ID = @a

end

close fc --关闭游标

deallocate fc  --释放游标

end

 

exec dbo.UpdateState  --调用游标,执行

6.   表数据结构如下图1,想要获得重复的值并且去除完全重复的行,得到结果如下图2

 

   图1                           2

答:

select distinct * into #temp from Text1 where ID in (select ID from Text1 group by ID having count(*)>1)

select * from #temp where ID in (select ID from #temp group by ID having count(*) > 1)

drop table #temp               -----别忘了删除临时表哦!

阅读(500) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~