如果查询没有返回结果,我可以设置变量吗?
DECLARE @Output AS VARCHAR(MAX);
SELECT @Output = 'Old';
SELECT @Output = 'New' WHERE 0 = 1;
PRINT @Output;
输出值为:旧
预期值为: NULL
答案 0 :(得分:4)
"inputDescriptors": [
{
"id": "connection",
"name": "Artifactory service",
"inputMode": "combo",
"isConfidential": false,
"hasDynamicValueInformation": true,
"validation": {
"isRequired": true,
"dataType": "string",
"maxLength": 300
}
},
{
"id": "definition",
"name": "definition",
"description": "Name of the build.",
"inputMode": "combo",
"isConfidential": false,
"dependencyInputIds": [
"connection"
],
"validation": {
"isRequired": true,
"dataType": "string",
"maxLength": 300
}
},
{
"id": "buildNumber",
"name": "Build Number",
"description": "Number of the build.",
"inputMode": "combo",
"isConfidential": false,
"dependencyInputIds": [
"connection"
],
"validation": {
"isRequired": true,
"dataType": "string",
"maxLength": 300
}
}
],
"dataSourceBindings": [
{
"target": "definition",
"dataSourceName": "BuildNames",
"resultTemplate": "{ Value : \"{{uri}}\", DisplayValue : \"{{uri}}\" }"
},
{
"target": "versions",
"dataSourceName": "BuildNumbers",
"resultTemplate": "{ Value : \"{{uri}}\", DisplayValue : \"{{uri}}\" }"
},
{
"target": "latestVersion",
"dataSourceName": "BuildNumbers",
"resultTemplate": "{ Value : \"{{uri}}\", DisplayValue : \"{{uri}}\" }"
},
{
"target": "artifactDetails",
"resultTemplate": "{ Name: \"{{version}}\", downloadUrl : \"{{endpoint.url}}\" }"
},
{
"target": "buildNumber",
"dataSourceName": "BuildNumbers",
"resultTemplate": "{ Value : \"{{uri}}\", DisplayValue : \"{{uri}}\" }"
}
]
}
您得到DECLARE @Output AS VARCHAR(MAX);
SELECT @Output = 'Old';
SELECT @Output = 'New' WHERE 0 = 1;
PRINT @Output;
,因为变量已经具有该值,并且不会更新该值,因为在'Old'
子句中,您使用条件WHERE
,该条件将返回{{1 }},并且变量中的值不会更改。
0=1
将是错误的
FALSE
将为真
它与WHERE 0 = 1
因此,在您的情况下,值将始终为WHERE 0 <> 1
,也不会返回IF 0=1 THEN UpdateMyVar
或'Old'
。
我不知道您实际上打算做什么,但是如果您想返回'New'
,那么
NULL
答案 1 :(得分:0)
尝试一下:
DECLARE @Output AS VARCHAR(MAX);
SELECT @Output = 'Old';
SELECT @Output = CASE 0 WHEN 1 THEN 'New' ELSE NULL END
SELECT @Output;
答案 2 :(得分:0)
萨米人对发生的事情提供了很好的解释。
如果要确保已分配值,则需要确保查询返回该分配的一行。一种方法是使用聚合:
DECLARE @Output AS VARCHAR(MAX);
SELECT @Output = 'Old';
SELECT @Output = MAX('New') WHERE 0 = 1;
SELECT @Output;
答案 3 :(得分:0)
这就是在SQL Server中实现在SELECT
中分配变量的方式。正如@SMor在评论中所说,请使用SET
而不是SELECT
。
DECLARE @Output AS VARCHAR(MAX);
SET @Output = 'Old';
SET @Output = (SELECT 'New' WHERE 0 = 1);
-- this would change the @Output value to NULL
SELECT @Output;
SET
的唯一问题是它只能分配一个变量,而在SELECT
中可以同时分配多个变量。