首先,我必须提取Id的列表,条件为
SELECT Id
FROM TABLE1
WHERE Validity = 'Date' AND ExpiryDate < GETDATE();
这里我必须保留id列表作为字符串示例1,2,3或44,56,67,77等
然后我必须运行更新查询
UPDATE TABLE1
SET Status = 'Expired'
WHERE Validity = 'Date' AND ExpiryDate < GETDATE();
这里我必须保持记录受影响
然后我必须进行插入查询,我必须使用id列表和受UPDATE查询影响的记录并插入到新表中
INSERT INTO LicenseExpiryJobLog (Descr)
VALUES ('Detected IDs= { here comma seperated ids} Total rows updated = ');
如何在SQL Server的最终插入中获取2个变量?
答案 0 :(得分:2)
您可以使用OUPUT
子句:
DECLARE @ids TABLE (id INT)
UPDATE TABLE1
SET Status = 'Expired'
OUTPUT INSERTED.id INTO @ids
WHERE Validity = 'Date' AND ExpiryDate < GETDATE();
INSERT INTO LicenseExpiryJobLog (Descr)
SELECT
'Detected IDS = {' +
STUFF((
SELECT ',' + CONVERT(VARCHAR(10), id)
FROM @ids
FOR XML PATH('')
), 1, 1, '') + '}'
+ ' Total Rows Updated = ' + CONVERT(VARCHAR(10), COUNT(*))
FROM @ids
答案 1 :(得分:1)
你可以用很多方式做到这一点,但这是我的简单版本。
DECLARE @IDs VARCHAR(MAX)
DECLARE @ROW_COUNT INT
DECLARE @STR_LOG VARCHAR(MAX)
SELECT @IDs = COALESCE(@IDs + ', ', '') + Id FROM TABLE1 WHERE Validity='Date' AND ExpiryDate < GETDATE();
UPDATE TABLE1 SET Status=Éxpired WHERE Validity='Date' AND ExpiryDate < GETDATE();
SELECT @ROW_COUNT = @@ROWCOUNT
SET @STR_LOG = 'Detected IDs= ' + @IDs + ' Total rows updated = ' + CAST(@ROW_COUNT AS VARCHAR(5)) + ''
INSERT INTO LicenseExpiryJobLog (Descr) VALUES (@STR_LOG);