Skip to content
Advertisement

How to change this coding from SQL Server to be in PostgreSQL [closed]

This query is running successfully using Microsoft SQL Server Management Studio and I could not use it in PostgreSQL. I want a similar query to give the same result using PostgreSQL Note that: this will run on a table that contains 1 junior and 2 seniors. I want to use this query also if I have more juniors and seniors

DECLARE @Budget Int = 50000, @Seniors int = 0, @Juniors int = 0, @SeniorSalary int = 20000, @juniorSalary int = 10000
WHILE @Budget >= @juniorSalary
BEGIN
IF @Budget >= @SeniorSalary
BEGIN
SET @Budget = @Budget - @SeniorSalary;
SET @Seniors = @Seniors + 1;
END
ELSE IF @Budget >= @juniorSalary
BEGIN
SET @Budget = @Budget - @juniorSalary;
SET @Juniors = @Juniors + 1;
END
END
SELECT @Seniors AS [Seniors], @Juniors as [Juniors], @Budget As [RemainingBudget]

Advertisement

Answer

Your first mistake is assuming something runs in SQL Server it will Postgres (or any other DBMS) all the flow from that one. Further it is not a query it is a script, and the structure for a psql script is completely different from a T-sql script. I suggest you spend considerable time studying a couple Postgres Tutorials such as command line tutorial and PostgreSQLTutorial and/or others or !gasp! old technology – a book.

I appreciate that sometimes a problem is one of concept, like expecting a T-Sql script to run in Postgres. Therefore, I offer the following as a one-time demonstration to point you in the right direction. It is a translation to Postgres of your script, certainly not the only and perhaps not the best.

I leave its description to your research.

create or replace 
function developer_budget
       ( budget       integer  
       , seniorsalary integer
       , juniorsalary integer
       )
 returns table ( seniors    integer 
               , juniors    integer
               , remaining  integer 
               )
 language plpgsql 
as $$ 
declare
  seniors   integer  = 0;
  juniors   integer  = 0;
begin 
   while budget >= juniorsalary
   loop
      if budget >= seniorsalary then
         budget = budget - seniorsalary;
         seniors = seniors + 1;
      elsif budget >= juniorsalary then
         budget = budget - juniorsalary;
         juniors = juniors + 1;
      end if;
   end loop;

   return query select seniors,juniors, budget;
end;
$$;

select seniors   "Seniors"  
     , juniors   "Juniors"  
     , remaining "Remaining bubjet"
  from developer_budget( Budget       => 50000  
                       , SeniorSalary => 20000 
                       , JuniorSalary => 10000
                       );  
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement