T-SQL - 参数分配、数据检索和比较在一行中完成 - 这可能吗?
我想在T-SQL中做这样的事情,但它会返回一个错误:
DECLARE @Stock int
IF(SELECT @Stock = [Stock] FROM dbo.Products WHERE [ProductID] = 1) > 5
PRINT 'Stock is good: Current stock is ' + @Stock
ELSE
PRINT 'Order some more - we are below minimum stock'
返回的错误是:
消息 102,级别 15,状态 1,第 2 行: “=”附近的语法不正确。
我当然可以这样做:
DECLARE @Stock int
SELECT @Stock = [Stock] FROM dbo.Products WHERE [ProductID] = 1
IF(@Stock > 5)
PRINT 'Stock is good: Current stock is ' + @Stock
ELSE
PRINT 'Order some more - we are below minimum stock'
我不确定这是否只是 T-SQL 语言的工作方式,对此没有什么可做的。我基本上是在寻找一种编写更少代码的捷径:)
有人有一些好的想法吗?
I want to do something like this in T-SQL, but it will return an error:
DECLARE @Stock int
IF(SELECT @Stock = [Stock] FROM dbo.Products WHERE [ProductID] = 1) > 5
PRINT 'Stock is good: Current stock is ' + @Stock
ELSE
PRINT 'Order some more - we are below minimum stock'
The error returned is:
Msg 102, Level 15, State 1, Line 2:
Incorrect syntax near '='.
I can of course do something like this instead:
DECLARE @Stock int
SELECT @Stock = [Stock] FROM dbo.Products WHERE [ProductID] = 1
IF(@Stock > 5)
PRINT 'Stock is good: Current stock is ' + @Stock
ELSE
PRINT 'Order some more - we are below minimum stock'
I am not sure if it is just the way the T-SQL language works and there is nothing to do about it. I am basically looking for a shortcut to write less code :)
Anybody has some good ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MAX 聚合将返回一行 行,没有 GROUP BY (根据我的回答)
编辑:
无论如何,你永远不会从存储过程中打印..
A MAX aggregate will return one row without a GROUP BY (as per my answer here)
Edit:
You would never PRINT from a stored proc anyway..
假设您不打算稍后在过程中使用 @Stock,您可以执行以下操作:
如果您想稍后在过程中重用 @Stock,则必须执行多个语句。不能将赋值与在 T-SQL 中的同一语句中返回数据的语句组合起来。只需尝试查看错误即可:
Assuming you are not planning on using @Stock later in the procedure you can do:
If you wanted to reuse @Stock later in your procedure then you must do it multiple statements. You cannot combine an assignment with a statement that returns data in the same statement in T-SQL. One need only try to see the error: