您的位置:程序门 -> db2 -> 基础类



在线等:db2中如何实现静态sql中对查询条件运行动态选择(我用的sql在oracle中已实现,但db2中报错)?有答案即结贴!!


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


在线等:db2中如何实现静态sql中对查询条件运行动态选择(我用的sql在oracle中已实现,但db2中报错)?有答案即结贴!![已结贴,结贴人:abcatai]
发表于:2007-11-28 10:50:32 楼主
我写的静态sql是:
select   *   from   mytable   where   my_id   =   :id   and   (:name   is   null   or   my_name   =   :name)
其中带:的变量是我传过来的参数,实现动态判断的是这一句:(:name   is   null   or   my_name   =   :name)
即如果变量name是null值的话查询条件my_name   =   :name 就忽略
我在oracle中可以正确运行这个sql,但是在db2中报错:"sql语句包含无效参数标记的使用"

请问db2有什么静态sql语句实现这样查询条件动态判断?

发表于:2007-11-28 15:47:451楼 得分:20
my_name   =   case   :name   when   'null'   then   my_name   else   :name   end


当null   值,my_name   =my_name     相当于忽略
发表于:2007-11-28 17:27:372楼 得分:0
to   飞龙:
用你的建议后,报错:“语句包含无效参数标记的使用”
发表于:2007-11-29 10:09:053楼 得分:0
我测试了一下,好像没有问题,是不是你的参数传的不对啊

db2   =>   select   *   from   t_log

p_id               time                                               action
----------   --------------------------   ----------
101                 2007-11-20-14.32.32.718000   insert
101                 2007-11-20-15.22.51.765000   update
101                 2007-11-20-15.22.51.765000   update
103                 2007-11-20-15.24.49.640001   insert
102                 2007-11-20-15.48.40.546000   update
103                 2007-11-20-15.48.40.546000   update

db2   =>   select   *   from   t_log   where   p_id   ='101'   and   action   =   case   'null'   when   'null'   then   action   else   'insert'   end

p_id               time                                               action
----------   --------------------------   ----------
101                 2007-11-20-14.32.32.718000   insert
101                 2007-11-20-15.22.51.765000   update
101                 2007-11-20-15.22.51.765000   update

db2   =>   select   *   from   t_log   where   p_id   ='101'   and   action   =   case   'insert'   when   'null'   then   action   else   'insert'   end

p_id               time                                               action
----------   --------------------------   ----------
101                 2007-11-20-14.32.32.718000   insert
发表于:2007-11-29 10:34:134楼 得分:0
我在plc   里面测试也没有问题,可能是你的程序里面标记符号的问题,   注意   结束符等

strcpy(id,"101");
strcpy(name,"null");
EXEC   sql   select   count(*)   into   :inum   from   t_log   where       p_id=:id   and   action   =   case   :name   when   'null'   then   action   else   :name   end   ;
printf("case   1   inum=%2d\n",inum);

strcpy(id,"101");
strcpy(name,"insert");
EXEC   sql   select   count(*)   into   :inum   from   t_log   where       p_id=:id   and   action   =   case   :name   when   'null'   then   action   else   :name   end   ;
printf("case   2   inum=%2d\n",inum);


运行结果:

case   1   inum=   3
case   2   inum=   1


快速检索

最新资讯
热门点击