sql 语句遇到困难,大牛来帮忙看看,在线等
第一段语句 declare @year varchar set @year='2011' 使用变量进行数据查询。不能读取数据declare @a varchar
declare @year varchar
set @year='2011'
set @a='7'
if(@a='1')
begin
select T_class.class_id, T_class.class_name from
T_class inner join T_TeaClass on T_class.class_id=T_TeaClass.class_id
where T_TeaClass.Tea_id='1' and convert(varchar(15), datepart(year,T_TeaClass.reg_time))='2011' and datepart (month,T_TeaClass.reg_time) between 1 and 6
end
else
begin
select T_class.class_id, T_class.class_name from
T_class inner join T_TeaClass on T_class.class_id=T_TeaClass.class_id
where T_TeaClass.Tea_id='1' and @year=( convert(varchar(15), datepart(year,T_TeaClass.reg_time))) and datepart (month,T_TeaClass.reg_time) between 7 and 12
end
第二段代码,能够读取数据
declare @a varchar
set @a='7'
if(@a='1')
begin
select T_class.class_id, T_class.class_name from
T_class inner join T_TeaClass on T_class.class_id=T_TeaClass.class_id
where T_TeaClass.Tea_id='1' and convert(varchar(15), datepart(year,T_TeaClass.reg_time))='2011' and datepart (month,T_TeaClass.reg_time) between 1 and 6
end
else
begin
select T_class.class_id, T_class.class_name from
T_class inner join T_TeaClass on T_class.class_id=T_TeaClass.class_id
where T_TeaClass.Tea_id='1' and ’2011‘=( convert(varchar(15), datepart(year,T_TeaClass.reg_time))) and datepart (month,T_TeaClass.reg_time) between 7 and 12
end
小弟我要使用的是第一种方法,可为什么不行呢,帮帮忙呀,大哥们,急
--------------------编程问答-------------------- declare @year varchar set @year='2011'
print @year
----------------------------
得到的结果是2
----------------------------
@year 变量应该定义长度
declare @year varchar(5) --------------------编程问答-------------------- 局部变量
局部变量使用户自己定义的变量,它的作用范围近在程序内部。通常只能在一个批处理中或存储过程中使用,用来存储从表中查询到的数据,或当作程序执行过程中暂存变量使用。局部变量使用DECLARE语句定义,并且指定变量的数据类型,然后可以使用SET或SELECT语句为变量初始化;局部变量必须以“@”开头,而且必须先声明后使用。其声明格式如下:
DECLARE @变量名 变量类型[,@变量名 变量类型…]
其中变量类型可以是SQL Server 2000支持的所有数据类型,也可以是用户自定义的数据类型。
局部变量不能使用“变量=变量值”的格式进行初始化,必须使用SELECT或SET语句来设置其初始值。初始化格式如下:
SELECT @局部变量=变量值
SET @局部变量=变量值
比如在pubs数据库中使用名为@find的局部变量检索所有姓以Ring开头的作者信息,代码如下:
USE pubs
DECLARE @find varchar(30)
SET @find = 'Ring%'
SELECT au_lname, au_fname, phone
FROM authors
WHERE au_lname LIKE @find
执行结果:
au_lname au_fname phone
---------------------------------------- -------------------- ------------
Ringer Albert 801 826-0752
Ringer Anne 801 826-0752
注意:如果声明字符型的局部变量,一定要在变量类型中指明其最大长度,否则系统认为其长度为1。
--------------------编程问答-------------------- 楼主关键就是上面最后一句 --------------------编程问答-------------------- 以后定义varchar型的变量,注意要定义长度,不然,默认就是1
补充:.NET技术 , ASP.NET