用户定义的函数在sql中返回多个值

时间:2016-04-02 16:22:42

标签: sql

我在sql中有以下表格:

enter image description here

我想编写一个将Student_ID作为参数并从上表中返回Student_Name和Balance的函数。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

CREATE DEFINER=`root`@`localhost` PROCEDURE `myproc`(IN `id` INT)
NO SQL
SELECT student.Student_Name, account.Balance 
FROM student INNER JOIN account
ON student.Student_ID = account.Student_ID
WHERE student.Student_ID = id

你可以从phpmyadmin创建程序: How to write a stored procedure in phpMyAdmin?

答案 1 :(得分:1)

功能可以创建为:

CREATE FUNCTION function_name(@Student_ID int)
RETURNS @name_and_balanceTable TABLE 
(
    -- Columns returned by the function_name
    Name nvarchar(50),
    Balance int
)
AS 
-- Returns the Name and Balance for particular Student_ID
BEGIN
    -- Selecting the name and balance
    SELECT 
        @Name = st.Student_Name, 
        @Balance = ac.Balance
    FROM Student st JOIN Account ac ON st.Student_ID = ac.Student_ID 
    WHERE st.Student_ID = @Student_ID;

    -- Insert these value into table
    BEGIN
        INSERT @name_and_balanceTable
        SELECT @Name, @Balance;
    END;
    RETURN;
END;

这是针对sql-server的。 有关更多信息,请使用this link ...