尝试获取用户名可以查看的文档数

时间:2015-02-07 15:24:17

标签: sql function select count

首先我需要创建一个表(UserPermissions):

CREATE TABLE UserPermissions
(
Document varchar2(15),
UserName varchar(15)
);
INSERT INTO UserPermissions
Values('Policy', 'SYSTEM');
INSERT INTO UserPermissions
Values('Menu', 'JDOW');
INSERT INTO UserPermissions
Values('W2', 'USAM');
INSERT INTO UserPermissions
Values('Permissions', 'SYSTEM');
 INSERT INTO UserPermissions
Values('W2', ‘JDOW');
INSERT INTO UserPermissions
Values('Form 1040', 'USAM');
INSERT INTO UserPermissions
Values('Policy', 'JDOW');
INSERT INTO UserPermissions
Values('W2', 'SYSTEM');

然后,编写一个PL / SQL存储函数,该函数将用户名作为输入,并返回用户有权查看的文档数。如果表中没有用户名,则您的过程应返回“未找到用户”。 到目前为止,这就是我所拥有的:

CREATE or REPLACE FUNCTION user_documents_func (UserName varchar2)
RETURN int AS
num_views INT;
BEGIN
SET num_views = (select count(*) from userpermissions);
IF num_views > 0 THEN
RETURN UserName || ' can view ' || num_views || ' document(s).';
ELSE 
Dbms_output.put_line('Username not found!');
END IF;
END;
/
SET SERVEROUTPUT ON;

我在SELECT语句“丢失或无效选项”上收到错误。

我已经改变了

SET num_views = (select count(*) from userpermissions);

致:

SELECT num_views = count(*)  from userpermissions WHERE UserName;

并以这种方式声明num_views

CREATE or REPLACE FUNCTION user_documents_func (UserName varchar2, num_views int)

现在我收到错误“找不到FROM关键字”

1 个答案:

答案 0 :(得分:0)

您需要先声明变量然后再分配它。

DECLARE @num_views int; // thought as sql-server

BEGIN
SELECT @num_views = count(*)  from userpermissions WHERE UserName LIKE input_var ;

IF @num_views > 0 THEN
RETURN UserName || ' can view ' || num_views || ' document(s).';
ELSE 
Dbms_output.put_line('Username not found!');
END IF;