Files
medical-mall/doc_mall/consumer/sql/insert_default_skus.sql
2026-02-03 17:26:23 +08:00

41 lines
1.2 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- =====================================================================================
-- 为没有SKU的商品生成默认SKU
-- 说明购物车逻辑依赖SKU ID如果商品没有SKU数据前端生成的模拟SKU ID会导致数据库外键约束错误
-- =====================================================================================
DO $$
DECLARE
v_product RECORD;
v_sku_id UUID;
v_count INT := 0;
BEGIN
-- 遍历所有没有SKU的商品
FOR v_product IN
SELECT p.id, p.product_code, p.base_price, p.total_stock
FROM public.ml_products p
LEFT JOIN public.ml_product_skus s ON p.id = s.product_id
WHERE s.id IS NULL
LOOP
-- 生成默认SKU
INSERT INTO public.ml_product_skus (
product_id,
sku_code,
specifications,
price,
stock,
status
) VALUES (
v_product.id,
v_product.product_code || '-DEF',
'{"默认": "标准规格"}',
v_product.base_price,
v_product.total_stock,
1
);
v_count := v_count + 1;
END LOOP;
RAISE NOTICE '已为 % 个商品生成默认SKU', v_count;
END $$;