用SET命令捕获多行错误

来源:互联网 发布:比特币源码 编辑:程序博客网 时间:2024/05/22 04:35
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

象单行一样,解决多行的T-SQL返回的结果是一个好习惯。在T-SQL里使用局部变量得到返回的结果记录集,如果用SELECT子句就会掩饰潜在的问题。

 
如果代码只希望得到一个值,SELECT子句只会分配一个值,尽管实际上可能返回多个值。如果这种分配用SET 命令会发生错误。但是,当你希望得到单个值的记录时,用SET命令会使T-SQL代码更加鲁棒。

下面的脚本演示了这种情况:

CREATE TABLE SETTest
(Pkey INT NOT NULL
 CONSTRAINT pk_SETTest primary key,
Name  VARCHAR(30) NOT NULL
 CONSTRAINT df_col1 DEFAULT 1
)
GO
INSERT SETTest VALUES (1,'Mary Johnson')
INSERT SETTest VALUES (2,'John Highland')
INSERT SETTest VALUES (3,'Ashly Robertson')
INSERT SETTest VALUES (4,'Mary Johnson')
GO
DECLARE @myVar INT
SELECT @myVar = Pkey FROM SETTest WHERE Name = 'Mary Johnson'
GO
DECLARE @myVar INT  -- ERROR WILL BE GENERATED
SET @myVar = ( SELECT Pkey FROM SETTest WHERE Name = 'Mary Johnson' )
GO
DROP TABLE SETTest
GO

 <script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击