-- SQL Server 2022 初始化脚本
-- 创建示例数据库和用户

-- 创建示例数据库
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'SampleDB')
BEGIN
    CREATE DATABASE SampleDB;
    PRINT '数据库 SampleDB 创建成功';
END
ELSE
BEGIN
    PRINT '数据库 SampleDB 已存在';
END
GO

-- 使用 SampleDB 数据库
USE SampleDB;
GO

-- 创建示例表
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Users' AND xtype='U')
BEGIN
    CREATE TABLE Users (
        Id INT IDENTITY(1,1) PRIMARY KEY,
        Username NVARCHAR(50) NOT NULL UNIQUE,
        Email NVARCHAR(100) NOT NULL,
        CreatedDate DATETIME2 DEFAULT GETDATE(),
        IsActive BIT DEFAULT 1
    );
    PRINT '表 Users 创建成功';
END
ELSE
BEGIN
    PRINT '表 Users 已存在';
END
GO

-- 插入示例数据
IF NOT EXISTS (SELECT * FROM Users WHERE Username = 'admin')
BEGIN
    INSERT INTO Users (Username, Email) VALUES 
    ('admin', 'admin@example.com'),
    ('user1', 'user1@example.com'),
    ('user2', 'user2@example.com');
    PRINT '示例数据插入成功';
END
ELSE
BEGIN
    PRINT '示例数据已存在';
END
GO

-- 创建存储过程
IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'GetActiveUsers')
BEGIN
    EXEC('
    CREATE PROCEDURE GetActiveUsers
    AS
    BEGIN
        SET NOCOUNT ON;
        SELECT Id, Username, Email, CreatedDate
        FROM Users
        WHERE IsActive = 1
        ORDER BY CreatedDate DESC;
    END
    ');
    PRINT '存储过程 GetActiveUsers 创建成功';
END
ELSE
BEGIN
    PRINT '存储过程 GetActiveUsers 已存在';
END
GO

PRINT 'SQL Server 初始化完成！';
