在SQL上创建函数

时间:2019-03-08 20:55:33

标签: sql-server tsql

我要一遍又一遍地重复相同的查询。有没有一种方法可以在以下查询中创建一个函数并作为参数传递以使其更具可读性。

USE [ES]
      GO    
DECLARE @current_value AS BigInt;
DECLARE @s nvarchar(1000);

SELECT @current_value = (SELECT sequence_id FROM SEQUENCES where  seq='seq1')
   if (@current_value > '0')
   SET @s = N'
ALTER SEQUENCE seq1 RESTART WITH ' + CAST(@current_value AS nvarchar(10));
    EXEC (@s);

SELECT @current_value = (SELECT sequence_id FROM SEQUENCES where seq='seq2')
    if (@current_value > '0')
    SET @s = N'
ALTER SEQUENCE seq2 RESTART WITH ' + CAST(@current_value AS nvarchar(10));
    EXEC (@s);

SELECT @current_value = (SELECT sequence_id FROM SEQUENCES where seq='seq3')
   if (@current_value > '0')
    SET @s = N'
ALTER SEQUENCE seq3 RESTART WITH ' + CAST(@current_value AS nvarchar(10));
    EXEC (@s);
    GO

2 个答案:

答案 0 :(得分:1)

您的查询包含一些DDL子句,这些子句不适合用户定义的函数。 您应该为查询使用存储过程。

CREATE PROC myProc @current_value BIGINT, @s NVARCHAR(1000)
AS    
SELECT .... 
GO;

因此,此后,您的查询将是:

EXECUTE dbo.myProc @current_value = ... , @s = .....

答案 1 :(得分:0)

类似于表变量的东西可以代替函数起作用(请注意:我将@s更改为@sql,因此可以使用自己的@s):

USE [ES]
      GO    
DECLARE @current_value AS BigInt;
DECLARE @sql nvarchar(1000);
DECLARE @seq TABLE (seq NVARCHAR(4), idx INT)
INSERT INTO @seq (seq, idx)
VALUES ('seq1',1),('seq2',2),('seq3',3),('seq4',4)
DECLARE @i INT = 0
DECLARE @s NVARCHAR(4)

WHILE @i <= (SELECT COUNT(*) FROM @seq)
BEGIN
    SET @i = @i + 1
    SET @s = (SELECT seq from @seq WHERE idx = @i)
    SELECT @current_value = (SELECT sequence_id FROM SEQUENCES where seq=@s)

    if (@current_value > '0')
        SET @sql = N'
            ALTER SEQUENCE '+@s+' RESTART WITH ' + CAST(@current_value AS nvarchar(10));
    EXEC (@sql);
END