简体   繁体   中英

Use Function with multi conditions on BigQuery

ALTER FUNCTION [dbo].[studentinformation]
    (@name as varchar (50)= NULL
     @surname as varchar (50) = NULL
     @schoolsname as varchar = NULL)
RETURNS **NVARCHAR(255)** 
AS
BEGIN
    DECLARE @ret AS **NVARCHAR(255)** = NULL    

    --Condition 1
    SELECT @ret = name + " " + surname
    FROM dbo.dataset_red as rd WITH(NOLOCK)
    INNER JOIN dbo.dataset_blue as bl WITH(NOLOCK) on rd.dataset = bl.dataset
    WHERE red.dataset IS NOT NULL

    IF @ret IS NOT NULL
    BEGIN
        RETURN @ret
    END

    --Condition 2
    SELECT @ret = name + " " + surname
    FROM dbo.dataset_red as rd WITH(NOLOCK)
    LEFT OUTER JOIN dbo.dataset_green as gr WITH(NOLOCK) on rd.zone = gr.zone
    WHERE red.dataset IS NOT NULL

    IF @ret IS NOT NULL
    BEGIN
        RETURN @ret
    END

    --Condition 3
    SELECT @ret = name + " " + surname
    FROM dbo.dataset_red as rd WITH(NOLOCK)
    LEFT OUTER JOIN dbo.dataset_yellow as yl WITH(NOLOCK) on rd.zone = yl.zone
    WHERE red.dataset IS NOT NULL

    RETURN @ret
END

Describe my question:

  • I have function which is come from 3 condition that get value from different table.
  • This function has hierarchical order from condition 1 to Condition 3.

My question:

  • I need to convert this T-SQL function to BigQuery

To create a function with multiple conditions you can use CASE to check multiple conditions. Using this sample data I have 2 tables.

Table 1:

在此处输入图像描述

Table 2:

在此处输入图像描述

Consider the below approach where I made two conditions that will run a query when it returns a value. It will return null if don't match anything:

NOTE: Query below are for testing only and you can add more conditions. Use your own query per condition to achieve your goal.

CREATE TEMP FUNCTION getStudentInfo(firstname STRING, surname STRING, schoolname STRING)
AS (
(

    case 
        when -- 1st condition
            exists(select name from `my-project.sandbox.table1` where name = concat(firstname, ' ', surname))
        then 
            (select name from `my-project.sandbox.table1` where name = concat(firstname, ' ', surname))

        when -- 2nd condition
            exists(select name from `my-project.sandbox.table2` where name = concat(firstname, ' ', surname))
        then
            (select name from `my-project.sandbox.table2` where name = concat(firstname, ' ', surname))
    end
)

);

select getStudentInfo('chris', 'paul', 'phx') as match_1,
       getStudentInfo('lebron', 'james', 'lal') as match_2,
       getStudentInfo('michael', 'jordan', 'chi') as match_3,
       getStudentInfo('tim', 'duncan', 'sas') as match_4;

Sample output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM