如何使用sql脚本定义列类型

问题描述 投票:0回答:1

我正在尝试用 SQL (postgresql) 编写一个脚本,该脚本将检索一些表元数据并将其保存到变量中。

例如,我想声明 v_column_type 变量,因此,我希望 v_column_type 包含值“pk_column”(如果它是主键列)、“fk_column”(如果它是外键列)、“ indexed_column”(如果它是索引列)或“column”(在任何其他情况下)。

有什么方法可以提取此类元数据吗?我认为有关索引列的信息可以从 pg_indexes 中检索

sql postgresql
1个回答
0
投票
DO $$
DECLARE
    v_table_name text := 'your_table_name';  -- Replace with your table name
    v_column_name text := 'your_column_name';  -- Replace with your column name
    v_column_type text;
BEGIN
    -- Check if the column is a primary key
    IF EXISTS (
        SELECT 1
        FROM pg_constraint c
        JOIN pg_attribute a ON a.attnum = ANY(c.conkey) AND a.attrelid = c.conrelid
        JOIN pg_class t ON t.oid = c.conrelid
        WHERE c.contype = 'p'
        AND t.relname = v_table_name
        AND a.attname = v_column_name
    ) THEN
        v_column_type := 'pk_column';

    -- Check if the column is a foreign key
    ELSIF EXISTS (
        SELECT 1
        FROM pg_constraint c
        JOIN pg_attribute a ON a.attnum = ANY(c.conkey) AND a.attrelid = c.conrelid
        JOIN pg_class t ON t.oid = c.conrelid
        WHERE c.contype = 'f'
        AND t.relname = v_table_name
        AND a.attname = v_column_name
    ) THEN
        v_column_type := 'fk_column';

    -- Check if the column is indexed
    ELSIF EXISTS (
        SELECT 1
        FROM pg_index i
        JOIN pg_class t ON t.oid = i.indrelid
        JOIN pg_attribute a ON a.attnum = ANY(i.indkey) AND a.attrelid = i.indrelid
        WHERE t.relname = v_table_name
        AND a.attname = v_column_name
    ) THEN
        v_column_type := 'indexed_column';

    -- Default case
    ELSE
        v_column_type := 'column';
    END IF;

    -- Output the result (for debugging purposes)
    RAISE NOTICE 'The column type is: %', v_column_type;
END $$;
© www.soinside.com 2019 - 2024. All rights reserved.