Temporary Stored Procedures

Temporary stored procedure is a little known feature of SQL Server.  This article is an attempt to throw some light on this interesting feature.

Temporary stored procedures are like normal stored procedures but, as their name suggests, have fleeting existence. There are two kinds of temporary stored procedures local and global. Temporary stored procedures are created just like any other SPs; however the name must begin with a hash (#) for a local temporary SP and two hashes (##) for a global temporary stored procedure.

A local temporary stored procedure is available only in the current session and is dropped when the session is closed. A global temporary stored procedure is visible to all sessions and is dropped when the session of the user that created it is closed. If there are any executing versions of the global stored procedure when the creator session is closed, those are allowed to complete, but once they are done and the creator session is closed, no further execution of the global temporary stored procedure is allowed.

Aside from local and global temporary stored procedures, you can also create regular stored procs in tempdb. These only exist until sql server is restarted because tempdb is recreated each time server is restarted.

The following exercise illustrates these points. First, open a new query window and run the following script and keep the query window open.

-- Local Temporary Stored Procedure
CREATE PROC #HarshaTest
AS
DECLARE @Table TABLE ( col1 INT );

INSERT INTO @Table
 ( col1 )
VALUES ( 1),(2),(3),(4);

SELECT * FROM @Table

RETURN 0
GO

-- Global Temporary Stored Procedure
CREATE PROC ##HarshaTest
AS
DECLARE @Table TABLE ( col1 INT );

INSERT INTO @Table
 ( col1 )
 VALUES ( 1),(2),(3),(4);

SELECT * FROM @Table

RETURN 0

GO
USE tempdb
GO
-- Stored procedure in tempdb
CREATE PROC dbo.HarshaTest
AS
DECLARE @Table TABLE ( col1 INT );

INSERT INTO @Table
 ( col1 )
VALUES ( 1),(2),(3),(4);

SELECT * FROM @Table

RETURN 0

GO

 You should see this in Management Studio:

The picture shows stored procedures in tempdb while the session is active. Notice the long postfix that SQL Server automatically adds to the local temporary stored procedure. SQL Server adds some postfix to local temporary objects to distinquish the objects with the same name from different sessions.

Now, in the same window, execute the local & global temporary stored procedures that you created . Both will work and return results.

EXECUTE #HarshaTest;

EXECUTE ##HarshaTest;

The results should look like those shown below:

 

Keeping this window open, open a new query window and execute the procs again. You will notice that local temp stored proc will fail with ‘object not found' error, but global temporary stored proc will work, as shown below.

In the messages tab, you should see:

Msg 2812, Level 16, State 62, Line 1

Could not find stored procedure '#HarshaTest'.

Now close the window in which you ran the create proc scripts and execute the procs in another window. You will notice that both will fail with object not found error since the session is now closed.

Checking Management Studio 

The picture shows the procedures in tempdb after the session is closed. Note that local and global procs that were created don’t exist anymore.

An interesting observation about temp stored procedures is, since they are created in tempdb, they can be called from any database.SQL Server basically ignores database name and schema name in the case of temporary stored procedures.

For example, the following two commands work and return the same results . Note that [blah] is a non-existing db.

EXECUTE ##HarshaTest;

EXECUTE [blah].dbo.##HarshaTest;

If you are wondering if it is possible to create temporary functions or temporary views , unfortunately SQL Server does not support Temporary Functions and Temporary Views .

Example : The following SQL will throw an error 

CREATE FUNCTION #HarshaTempFunction()
RETURNS VARCHAR(100)

AS
BEGIN

RETURN('This is a Temporary Function');

END

The results are:

Msg 1074, Level 15, State 1, Line 1

Creation of temporary functions is not allowed.

Limitations:

  • Heavy use of temporary stored procedures can create contentionon system tables in tempdb . You also use sp_executesql instead of temporary procs. sp_executesql does not save information to system tables and hence there is no contention.

  • You cannot create CLR stored procedures/ functions as temporary objects.

Uses of Temporary Stored procedures:

One use for temporary stored procedures is code reuse and improved error handling when you don’t have object CREATE permissions in any of the databases to create stored procedures.

Example : In SSIS package SQL scripts, if the user doesn’t have object create permission but wants to take advantage of code reuse and execution plan caching features of stored procedures, he can create temporary stored procedures.

You can also use temporary procedures to test a stored procedure before actually creating it. Instead of creating and dropping a permanent stored proc, you can create a temporary stored proc and make it permanent after it performs satisfactorily .

During deployment, if you have a script that uses repetitive code, you can create a temporary stored proc at the beginning of the script and reuse it throughout the script. The temporary stored proc is dropped when the connection is closed so you will not have code lying around after deployment.

For example:

CREATE PROC #tempDeploymentRowsInserted
@stepId INT,
@rowCount INT
AS
BEGIN 
INSERT INTO RowsInsertedDuringDeploymentSteps(StepID,RowsCount) VALUES (@stepId, @rowCount);

END

GO
DECLARE @rowCount INT;

--{Code}

SET @rowCount = @@ROWCOUNT;
EXEC #tempDeploymentRowsInserted 1,@rowCount;

--{Code}

SET @rowCount = @@ROWCOUNT;
EXEC #tempDeploymentRowsInserted 2,@rowCount;

--{Code}

SET @rowCount = @@ROWCOUNT;
EXEC #tempDeploymentRowsInserted 3,@rowCount;

--Code

Temporary stored procedures are useful when connecting to earler versions of SQL server that do not support reuse of execution plans for T-SQL statement or batches( < SQL server 7.0 ) . You can take advantage of execution plans using temporary stored procedures. ODBC Drivers for instance make use of temporary stored procedures.

One use of global temporary stored procedures is code reuse during coordinated collaborative work. When a team is working on something (maintenance work, etc) and there is a code segment that everyone uses during the duration of the work, it can be put in a global temporary stored procedure. After the work is done, the user that created the global temporary variable can close the session and there will not be any vestigial code on the server.

In summary, temporary stored procedures are analogous to temporary tables. They can be use to store code that can be reused throughout the life of your connection.

深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值