0

I convert from SQL Server to PostgreSQL

I used ADO.NET

My queries include defined variables inside the query

For example this

 SqlCommand sqlCommand=new SqlCommand(
                @"declare @tempId bigint 
                select top 1 @tempId = col1 from table 
                if @tempId is not null
                begin 
                select ...
                end 
                else 
                begin 
                select ...
                end ")

How do I do it with NpgsqlCommand?

2
  • 2
    SQL (the query language) doesn't support variables or an IF command and Postgres has no extension to the SQL language to support that. You will have to do that conditional logic in Ado.net or write a stored procedure using PL/pgSQL where variables and conditional execution is supported. Commented May 3, 2022 at 6:14
  • @a_horse_with_no_name Is it possible to do this without Saved SP? Commented May 3, 2022 at 8:05

1 Answer 1

1

You can use a PostgreSQL anonymous code DO block to execute a fragment of procedural code, see the PG docs.

Example:

DO $$DECLARE r record;
BEGIN
    FOR r IN SELECT table_schema, table_name FROM information_schema.tables
             WHERE table_type = 'VIEW' AND table_schema = 'public'
    LOOP
        EXECUTE 'GRANT ALL ON ' || quote_ident(r.table_schema) || '.' || quote_ident(r.table_name) || ' TO webuser';
    END LOOP;
END$$;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.