Microsoft Fabric API for GraphQL,可以轻松地从 Fabric SQL 数据库和其他 Fabric 数据源(如数据仓库和 Lakehouse)查询和改变数据,并具有强类型架构和丰富的查询语言,使开发人员无需编写自定义服务器代码即可创建直观的 API。 可以使用存储过程来封装和重用复杂的业务逻辑,包括输入验证和数据转换。
在此示例中,我们了解如何使用存储过程注册新产品,以及用于验证、格式设置和 ID 生成的服务器端逻辑,这些逻辑都通过 Fabric 中的 GraphQL 突变公开。
开始
我们首先在 Fabric 中创建 SQL 数据库:
- 在 Fabric 工作区中,选择“ 新建项 ”,然后选择 “SQL 数据库”(预览)。
- 为数据库指定名称,然后选择 “示例数据 ”以快速创建数据库中所需的所有表和数据。
方案:注册新产品
假设你想要使用以下项创建新产品:
- 定价逻辑验证(例如。ListPrice > StandardCost)
- 转换(例如,大写产品名称的首字母,去掉空格后大写产品编号)
- 产品编号生成(通过递增最新的产品编号)
步骤 1:创建存储过程
下面是一个 T-SQL 存储过程,用于封装我们需要的所有业务逻辑。 在 SQL 数据库中,单击“ 新建查询 ”并使用以下语句:
CREATE PROCEDURE SalesLT.RegisterProduct
@Name nvarchar(50),
@ProductNumber nvarchar(25),
@StandardCost money,
@ListPrice money,
@SellStartDate datetime
AS
BEGIN
SET NOCOUNT ON;
SET IDENTITY\_INSERT SalesLT.Product ON;
-- Validate pricing logic
IF @ListPrice <= @StandardCost
THROW 50005, 'ListPrice must be greater than StandardCost.', 1;
-- Transform product name: capitalize first letter only
DECLARE @CleanName nvarchar(50);
SET @CleanName = UPPER(LEFT(LTRIM(RTRIM(@Name)), 1)) + LOWER(SUBSTRING(LTRIM(RTRIM(@Name)), 2, 49));
-- Trim and uppercase product number
DECLARE @CleanProductNumber nvarchar(25);
SET @CleanProductNumber = UPPER(LTRIM(RTRIM(@ProductNumber)));
-- Generate ProductID by incrementing the latest existing ID
DECLARE @ProductID int;
SELECT @ProductID = ISNULL(MAX(ProductID), 0) + 1 FROM SalesLT.Product;
INSERT INTO SalesLT.Product (
ProductID,
Name,
ProductNumber,
StandardCost,
ListPrice,
SellStartDate
)
OUTPUT
inserted.ProductID,
inserted.Name,
inserted.ProductNumber,
inserted.StandardCost,
inserted.ListPrice,
inserted.SellStartDate
VALUES (
@ProductID,
@CleanName,
@CleanProductNumber,
@StandardCost,
@ListPrice,
@SellStartDate
);
END;
单击“ 运行 ”以测试执行。 你会注意到 SalesLT 数据库中的“存储过程”文件夹下的新存储过程 RegisterProduct。 使用以下查询测试过程逻辑:
DECLARE @RC int
DECLARE @Name nvarchar(50)
DECLARE @ProductNumber nvarchar(25)
DECLARE @StandardCost money
DECLARE @ListPrice money
DECLARE @SellStartDate datetime
-- TODO: Set parameter values here.
Set @Name = 'test product'
Set @ProductNumber = 'tst-0012'
Set @StandardCost = '10.00'
Set @ListPrice = '9.00'
Set @SellStartDate = '2025-05-01T00:00:00Z'
EXECUTE @RC = \[SalesLT\].\[RegisterProduct\]
@Name
,@ProductNumber
,@StandardCost
,@ListPrice
,@SellStartDate
GO
步骤 2:创建 GraphQL API
从 SQL 表创建 API 是快速、简单且直接的。 只需在 SQL 数据库功能区中单击 “用于 GraphQL 的新 API ”按钮,并为 API 命名。
接下来,选择数据库中的 SalesLT 表和刚刚创建的存储过程,然后单击“ 加载:
GraphQL API、架构和所有解析程序根据 SQL 表和存储过程在数秒内自动生成。
步骤 3:从 GraphQL 调用过程
API 准备就绪后,存储过程将作为一个变更在 Fabric GraphQL 模式中可用。 去查询编辑器并执行以下变更:
mutation {
executeRegisterProduct (
Name: " graphQL swag ",
ProductNumber: "gql-swag-001",
StandardCost: 10.0,
ListPrice: 15.0,
SellStartDate: "2025-05-01T00:00:00Z"
) {
ProductID
Name
ProductNumber
StandardCost
ListPrice
SellStartDate
}
}
提示
- Fabric GraphQL 自动生成存储过程的突变字段,这些存储过程返回过程输出中定义的结果集。
- 业务逻辑位于过程中,而不是客户端。
- 仅当不依赖于标识列时,才使用确定性 ID 生成。
通过 Fabric API 公开存储过程可让你在 SQL 中为数据定义可靠、一致的规则,并通过 GraphQL 完全访问它。