bill-ramos-rmoswi / babelfish_postgresql_towel

Bill Ramos's knowledge base for tips, tricks, and best practices for migrating SQL Server solutions to Babelfish for PostgreSQL and the open-source WiltonDB for Windows
Apache License 2.0
1 stars 1 forks source link

Getting Issue in conditional statement in procedure #20

Open JayakumarEMIS opened 1 week ago

JayakumarEMIS commented 1 week ago

Hi @bill-ramos-rmoswi, there is an issue in bebalfish, I have one procedure in that procedure and one condition check database exists and if exists i am getting data from the database, otherwise it execute else block, in my scenario i don't have databse and goes into else block, even though if condition not executed i am getting database not exists, but this works in sql kindly check and help me i added the query and results below

`CREATE PROCEDURE [dbo].[Test] AS

BEGIN if exists ( select 1 from sys.databases where name = 'payloaddb' ) begin SELECT * FROM payloaddb.dbo.Payload end; else begin select 1 end; END

EXEC [dbo].[Test] `

Sql Result: image

Babefish Result: image

staticlibs commented 1 week ago

@JayakumarEMIS

Yes, Babelfish checks for DB existence before considering if the branch is active. I've filed #71 to track this in WiltonDB.

Currently workaround is to use dynamic SQL for queries that refer to the DB that may not exist.

JayakumarEMIS commented 1 week ago

Thanks @staticlibs , can you please inform once the bug is fix, and also can you please help me to write sample dynamic query how the below query is workable

`CREATE PROCEDURE [dbo].[Test] AS

BEGIN if exists ( select 1 from sys.databases where name = 'payloaddb' ) begin SELECT * FROM payloaddb.dbo.Payload end; else begin select 1 end; END`

staticlibs commented 1 week ago

@JayakumarEMIS

Fix in WiltonDB 3.3 is not planned, there is limited support for cross-DB queries in that version, for example such queries are not supported at all in views and function.

Something like this should work:

CREATE PROCEDURE [dbo].[Test]
AS
BEGIN
if exists ( select 1 from sys.databases where name = 'payloaddb' )
begin
    exec('SELECT * FROM payloaddb.dbo.Payload')
end;
else
begin
    select 1
end;
END
JayakumarEMIS commented 1 week ago

Sure thanks @staticlibs, seems dynamic sql is working, this issue i found during one module testing, if the same issue arise other modules in my application, if occur i will apply this fix there also