Invoke a scalar function from python

515 views Asked by At

I see a lot of info about how to invoke a stored procedure to return, say, the key of a record that was inserted from Python to an SQL table using the fetchval() function.

However, I would like to invoke an SQL UDF.

The SQL is

ALTER FUNCTION udf_get_gleif_last_entity_lei
(

)
RETURNS nvarchar(500)
AS
BEGIN
    DECLARE @last_lei nvarchar(500)

    SELECT @last_lei = LEI FROM dbo.gleif_level1_entities WHERE id=(SELECT max(id) FROM dbo.gleif_level1_entities);

    RETURN @last_lei
END

I can confirm this works by invoking it through a query window:

declare @result nvarchar(500)
exec @result = dbo.udf_get_gleif_last_entity_lei
print(@result)

Now I want to invoke this through python. I thought it would work the same way as invoking a stored procedure:

[conn, cursor] = init_connection(server_name, db_name)
sql_str = "exec dbo.udf_get_gleif_last_entity_lei"
return_value = cursor.execute(sql_str).fetchval()
print("return_value = ", return_value)

Unfortunately that doesn't want to work. It errors on the cursor.execute() command.

pyodbc.ProgrammingError: No results. Previous SQL was not a query.

This makes me think that UDFs must be executed a different way. Or maybe I change this to a regular stored procedure. I can make that work. Anyway: Can pyodbc invoke UDFs? If so, how?

Addendum: Yes. This definitely works when I change the UDF to a stored procedure.

0

There are 0 answers