我有以下宣告:
IF (SELECT IntId
FROM MyTable
WHERE Name = 'Jon') IS NOT NULL
BEGIN
PRINT IntId
END
ELSE
BEGIN
PRINT 'Not an id'
END
IntId 是表的 PK,我想看看它是否存在,Name = Jon但它超出了范圍,那么我如何讓它列印?
uj5u.com熱心網友回復:
如果使用 SQL Server 2017 ,在這種情況下您可以做的是使用string_agg如果有重復,它將為您提供所有 ID 值:
declare @id varchar(max);
select @id=String_Agg(IntId, ',')
from MyTable
where [Name] = 'jon';
print case when @id is null then 'not an id' else @id end;
uj5u.com熱心網友回復:
有幾種方法可以實作這一點。
使用變數
DECLARE @IntId int;
SET @IntId = (
/* I added a TOP 1, in case your query returns more
than one row. If it does return more than 1 row, you're
looking at looping data to a print statement, and that's
a different question. */
SELECT TOP 1 IntId
FROM MyTable
WHERE Name = 'Jon'
ORDER BY IntId
)
IF @IntId IS NOT NULL
BEGIN
PRINT @IntId
END
ELSE
BEGIN
PRINT 'Not an id'
END
如果存在,請選擇一些東西
IF EXISTS (SELECT 1 FROM MyTable WHERE Name = 'Jon') IS NOT NULL
BEGIN
SELECT IntId FROM MyTable WHERE Name = 'Jon'
END
ELSE
BEGIN
PRINT 'Not an id'
END
uj5u.com熱心網友回復:
你有兩個選擇。由于性能問題,不建議再次重復該選擇。第二個它存盤在一個變數中。
Declare @IntId int
SELECT @IntId = IntId
FROM MyTable
WHERE Name = 'Jon'
IF (@IntId) IS NOT NULL
BEGIN
PRINT @IntId
END
ELSE
BEGIN
PRINT 'Not an id'
END
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437060.html
上一篇:加入兩個表...沒有JOIN
下一篇:如何將3列交叉連接在一起?
