我可以声明一个局部变量不为空吗? [英] Can I declare a local variable not null?
问题描述
在 T-SQL 中,我声明了一个用于某些查询的局部变量,如下所示:
In T-SQL, I declare a local variable for use with some query like so:
DECLARE @var_last datetime;
SET @var_last = (SELECT TOP(1) col_date FROM tbl_dates ORDER BY col_date);
在我正在测试的应用程序中,此查询返回 NULL 将是一个错误,并且如果查询返回崩溃错误,则是可取的.
In an application I'm testing, it would be an error for this query to return NULL, and it's desirable for the query to return a crash error if it were.
我想将 @var_last
设置为 NOT NULL
但语法...
I'd like to set @var_last
to be NOT NULL
but the syntax...
DECLARE @var_last datetime NOT NULL;
...无效.我可以对查询的返回值写一个简单的检查,看看它是否为 NULL,如果是错误,但我的问题是,是否不能将局部变量声明为 NOT NULL?
...is invalid. I can write a simple check on the return of the query to see if it's NULL, and error if it is, but my question is, is it not possible to declare a local variable as NOT NULL?
推荐答案
没错,根据 DECLARE @local_variable
的文档,可在:http://technet.microsoft.com/en-us/library/ms188927.aspx,它不接受<代码>NULL |NOT NULL 参数 -- 这些仅对列定义有效.
That's right, according the documentation for the DECLARE @local_variable
, available at: http://technet.microsoft.com/en-us/library/ms188927.aspx, it doesn't accept a NULL | NOT NULL
parameter -- those are only valid for column definitions.
如果您想在返回 NULL
时停止执行,则测试 NULL
,如果是,则测试 RAISERROR
;请参阅:http://technet.microsoft.com/en-us/library/ms178592.aspx.
If you want to stop execution if you return a NULL
, then test for NULL
and, if it is, RAISERROR
; see: http://technet.microsoft.com/en-us/library/ms178592.aspx.
这篇关于我可以声明一个局部变量不为空吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!