--简单示例--动态查询指定表的内容,表名由参数确定
create proc p_qry
@要查询的表名 sysname
as
declare @s varchar(8000)
set @s='select * from ['+@要查询的表名+']'
exec(@s)
go--调用
exec p_qry 'sysobjects'
create proc p_qry
@要查询的表名 sysname
as
declare @s varchar(8000)
set @s='select * from ['+@要查询的表名+']'
exec(@s)
go--调用
exec p_qry 'sysobjects'
declare @y varchar(20)
set @x='hou'
select @y=''+@x+''
select @y
和
declare @x varchar(10)
declare @y varchar(20)
set @x='hou'
select @y=@x
select @y
他们的结果是一样的啊,那为何还用''+@x+'',还有''+ +''其做用是什么呢?
declare @y varchar(20)
set @x='hou'
select @y='%'+@x+'%'
select @y这样用?不知道
可能有别的用法。:)
declare @y varchar(20)
set @x='hou'
select @y=''+@x+''
select @y
--返回 houdeclare @x varchar(10)
declare @y varchar(20)
select @y=@x
select @y
--返回NULLdeclare @x varchar(10)
declare @y varchar(20)
select @y=''+@x+''
select @y
--返回空符串如果是這樣,可用 isnull函數處理
declare @x varchar(10)
declare @y varchar(20)
select @y=isnull(@x,'')
select @y
--返回空符串
if exists (select * from dbo.sysobjects where id = object_id(N'[tb]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [tb]
GOcreate table tb(单位名称 varchar(10),日期 datetime,销售额 int)
insert into tb
select 'A单位','2001-01-01',100
union all select 'B单位','2001-01-02',101
union all select 'C单位','2001-01-03',102
union all select 'D单位','2001-01-04',103
union all select 'E单位','2001-01-05',104
union all select 'F单位','2001-01-06',105
union all select 'G单位','2001-01-07',106
union all select 'H单位','2001-01-08',107
union all select 'I单位','2001-01-09',108
union all select 'J单位','2001-01-11',109/*-- 要求结果
日期 A单位 B单位 C单位 D单位 E单位 F单位 G单位 H单位 I单位 J单位
---------- ----- ----- ----- ----- ----- ----- ---- ---- ---- ------
2001-01-01 100 0 0 0 0 0 0 0 0 0
2001-01-02 0 101 0 0 0 0 0 0 0 0
2001-01-03 0 0 102 0 0 0 0 0 0 0
2001-01-04 0 0 0 103 0 0 0 0 0 0
2001-01-05 0 0 0 0 104 0 0 0 0 0
2001-01-06 0 0 0 0 0 105 0 0 0 0
2001-01-07 0 0 0 0 0 0 106 0 0 0
2001-01-08 0 0 0 0 0 0 0 107 0 0
2001-01-09 0 0 0 0 0 0 0 0 108 0
2001-01-11 0 0 0 0 0 0 0 0 0 109
--*/-- 常规处理方法
declare @sql nvarchar(4000)
set @sql='select 日期=convert(varchar(10),日期,120)'
select @sql=@sql+',['+单位名称
+']=sum(case 单位名称 when '''+单位名称+''' then 销售额 else 0 end)'
from(select distinct 单位名称 from tb) a
exec(@sql+' from tb group by convert(varchar(10),日期,120)')
我的意思是既然用select @y=@x就可以完成对@Y的赋值
为何还有select @y=''+@x+''这种方法呢?这个方法不是很麻烦吗?
还是在有的动态SQL中只能用''+@x+''这种形式呢?举个只能用用''+@x+''不能用@X的例子好吗?请各位高手讲解。
不過真處理NULL值不需兩邊都加單引號。