Ubuntu 上使用 SQL Server 存储过程教程
一 环境准备与连接
sqlcmd -S localhost -U your_username -P your_password。如需图形化管理,可安装 SQL Server Management Studio(SSMS) 或在 Visual Studio Code 中安装 SQL Server(mssql) 扩展进行连接与编写。以上工具与连接方式适用于在 Linux 环境下进行存储过程的创建与管理。二 基本语法与第一个存储过程
CREATE PROCEDURE ProcedureName
@Parameter1 DataType,
@Parameter2 DataType,
...
AS
BEGIN
-- SQL statements here
END;
GO
USE YourDatabase;
GO
CREATE PROCEDURE GetAllEmployees
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM Employees;
END;
GO
EXEC GetAllEmployees;
USE YourDatabase;
GO
CREATE PROCEDURE AddNumbers
@Number1 INT,
@Number2 INT,
@Sum INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET @Sum = @Number1 + @Number2;
END;
GO
DECLARE @Result INT;
EXEC AddNumbers @Number1 = 5, @Number2 = 10, @Sum = @Result OUTPUT;
SELECT @Result AS Result;
三 管理存储过程
EXEC sp_help 'AddNumbers';
ALTER PROCEDURE AddNumbers
@Number1 INT,
@Number2 INT,
@Sum INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET @Sum = @Number1 + @Number2 * 2; -- 修改逻辑
END;
GO
DROP PROCEDURE AddNumbers;
GO
四 在 Ubuntu 终端的完整操作示例
-- 1) 连接数据库
sqlcmd -S localhost -U sa -P '<YourStrong@Passw0rd>'
-- 2) 创建数据库与表
CREATE DATABASE DemoDB;
GO
USE DemoDB;
GO
CREATE TABLE Products (
Id INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(100),
Price DECIMAL(10,2)
);
GO
INSERT INTO Products (Name, Price) VALUES
(N'Apple', 3.50),
(N'Banana', 2.00),
(N'Cherry', 5.00);
GO
-- 3) 创建带参数的存储过程:按价格区间查询
CREATE PROCEDURE GetProductsByPrice
@MinPrice DECIMAL(10,2),
@MaxPrice DECIMAL(10,2)
AS
BEGIN
SET NOCOUNT ON;
SELECT Id, Name, Price
FROM Products
WHERE Price BETWEEN @MinPrice AND @MaxPrice
ORDER BY Price;
END;
GO
-- 4) 调用存储过程
EXEC GetProductsByPrice @MinPrice = 2.00, @MaxPrice = 4.00;
GO
五 常见问题与最佳实践