查询不是按预期方式返回值

时间:2015-10-27 09:14:49

标签: sql oracle plsql

我试图从表'TABLE1'中计算特定列,即col1。

以下是我要点击的查询

select count(col1) into col_data
 from (SELECT TABLE_NAME from USER_TABLES where TABLE_NAME = 'table1');

以下错误我正在

Error starting at line 1 in command:
select count(COL1) from (SELECT TABLE_NAME from USER_TABLES where TABLE_NAME = 'TABLE1')
Error at Command Line:1 Column:13
Error report:
SQL Error: ORA-00904: "COL1": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:

注意:请告诉我如何使用from子句

的变量

1 个答案:

答案 0 :(得分:1)

如果要计算表TABLE1的列col1中的值的数量,那么你应该写

select convert(char(5),sp.spid) as SPID
        ,  CASE lower(sp.status)
                 When 'sleeping' Then lower(sp.status)
                 Else  upper(sp.status)
              END as Status
        , convert(sysname, rtrim(sp.loginame)) as LOGIN
        , CASE sp.hostname
                 When Null  Then '  .'
                 When ' ' Then '  .'
                 Else    rtrim(sp.hostname)
              END as HostName
        , CASE isnull(convert(char(5),sp.blocked),'0')
                 When '0' Then '  .'
                 Else isnull(convert(char(5),sp.blocked),'0')
              END as BlkBy
        , case when sp.dbid = 0 then null when sp.dbid <> 0 then db_name(sp.dbid) end as DBName
        , sp.cmd as Command
        , sp.cpu as CPUTime
        , sp.physical_io as DiskIO
        , sp.last_batch as LastBatch
        , sp.program_name as ProgramName 
        from master.dbo.sysprocesses sp (nolock)
  ;

如果你想使它成为通用的,这样你可以对任何TABLE和COLUMN进行计数,并希望在运行时提供详细信息,你可以使用以下

select count(col1) from TABLE1 ;

一旦你在你的模式中创建了这个功能,你可以做类似

的事情
create or replace function get_count(table_name varchar2 , column_name varchar2)
return number
is
cnt number ;
begin
execute immediate 'select count('||column_name||') from '||table_name into     cnt ;
return cnt;
exception when others then
return 0;
end get_count;