使用游标建立视图的一个实例(涉及多张表)
declare @x varchar(2000)
declare @y varchar(2000)
declare @str varchar(max)
declare @sql varchar(max)
declare @flag int --标记循环次数
set @flag=1
set @str=‘‘--保存建立视图的语句
DECLARE @table_name varchar(2000)
DECLARE cursor2 CURSOR FOR --定义游标cursor2
SELECT name FROM (select name from sysobjects where xtype=‘U‘ and name not like ‘%copy%‘ and name not like ‘[A-Z]%‘ and name not like ‘[a-z]%‘ ) t -- 共84条记录
OPEN cursor2 --打开游标
FETCH NEXT FROM cursor2 INTO @table_name
WHILE @@FETCH_STATUS=0 --判断是否成功获取数据
BEGIN
set @sql=‘select * from syscolumns where id=object_id(‘‘‘+ @table_name +‘‘‘) and name=‘‘is_delete ‘‘‘--单引号需要转义,用两个单引号表示
set @+1
exec(@sql)
if @@rowcount=1 --@@rowcount返回受上一语句影响的行数,判断是否有1行受影响
begin
if @flag<82 --多个条件需要加()
begin
set @x=‘ select name=‘‘‘_name+‘‘‘, zero=(SELECT count(*) from ‘+ @table_name +‘ where is_delete=0),one=(SELECT count(*) from ‘+ @table_name +‘ where is_delete=1),two=(SELECT count(*) from ‘+ @table_name +‘ where is_delete=2),three=(SELECT count(*) from ‘+ @table_name +‘ where is_delete=3) union ‘
set @+@x
print @flag
print @str
end
else
begin
print @flag
set @y=‘select name=‘‘‘_name+‘‘‘, zero= (SELECT count(*) from ‘+ @table_name +‘ where is_delete=0),one=(SELECT count(*) from ‘+ @table_name +‘ where is_delete=1),two=(SELECT count(*) from ‘+ @table_name +‘ where is_delete=2),three=(SELECT count(*) from ‘+ @table_name +‘ where is_delete=3) ‘
set @str=‘create view tb as ‘+@y
print @str
exec (@str)
break
end
end
FETCH NEXT FROM cursor2 INTO @table_name
END
CLOSE cursor2 --关闭游标
DEALLOCATE cursor2 相关推荐
liuyang000 2020-09-25
ztyzly00 2020-07-21
FellowYourHeart 2020-10-05
好记忆也需烂 2020-07-28
专注前端开发 2020-10-21
苏康申 2020-11-13
vitasfly 2020-11-12
oraclemch 2020-11-06
赵继业 2020-08-17
whyname 2020-08-16
Seandba 2020-08-16
dbasunny 2020-08-16
拼命工作好好玩 2020-08-15
langyue 2020-08-15
写程序的赵童鞋 2020-08-03
Accpcjg 2020-08-02
tydldd 2020-07-30