这发生在第4行。
UPDATE CashBalances
SET Balance1=0,
Balance2=0
WHERE PID=100040
AND Date='20081024'
IF @@ROWCOUNT=0
INSERT INTO CashBalances(PID,Date,BalanceCode,Balance1,Balance2,CCY)
VALUES (100040 ,'20081024', (SELECT TOP 1 balancecode
FROM cashbalances
WHERE date=(SELECT MAX(Date)
FROM CashBalances
WHERE PID=100040)
IF @@ROWCOUNT = 0 SELECT 'I' AS balancecode),0,0,' ')
我正在尝试检索一个平衡代码,其中日期是特定pid的最大值。 如果返回零行,则返回'I'作为余额代码。
感谢。
答案 0 :(得分:1)
只需创建另一个valiable然后插入它:
IF (SELECT COUNT(PID) FROM CashBalances WHERE PID=100040) > 0
BEGIN
UPDATE CashBalances SET Balance1=0,Balance2=0 WHERE PID=100040 AND Date='20081024';
END
ELSE
BEGIN
--Here your create it, could be that you use different type
DECLARE @ConditionalValue NVARCHAR(MAX) = 'I';
--Here you set it with a right value that you need on condition
IF @@ROWCOUNT > 0
SET @ConditionalValue = (SELECT TOP 1
FROM cashbalances
WHERE date=(SELECT MAX(Date)
FROM CashBalances
WHERE PID=100040))
--Insert your final value
INSERT INTO CashBalances(PID, Date, BalanceCode, Balance1, Balance2, CCY)
VALUES (100040 ,'20081024', @ConditionalValue,0,0,' ')
END
答案 1 :(得分:1)
坚持选择或值。不是都。正如Arvo所提到的,你不能在查询中使用if。你可以改用案例,但你不需要它。
update CashBalances
set Balance1=0, Balance2=0
where PID=100040 AND Date='20081024'
if @@ROWCOUNT=0
Begin
declare @Balancecode char(1)='I'
select top 1 @Balancecode = balancecode
from cashbalances cb
where PID=100040
order by date desc
insert into CashBalances(PID,Date,BalanceCode,Balance1,Balance2,CCY)
values (100040 ,'20081024', @balanceCode,0,0,' ')
end
答案 2 :(得分:0)
您可以采用不同的方式进行此操作。
如果PID=100040 AND Date='20081024'
上没有数据,则插入查询将起作用。
DECLARE @Query NVARCHAR(MAX) = '
INSERT INTO CashBalances(PID,Date,BalanceCode,Balance1,Balance2,CCY)
VALUES
(
100040 ,
''20081024'',
COALESCE ((SELECT TOP 1 balancecode FROM cashbalances WHERE date=(SELECT MAX(Date) FROM CashBalances WHERE PID=100040), ''I'',
0,
0,
'' ''
)';
SELECT @Query = 'UPDATE CashBalances
SET Balance1=0,
Balance2=0
WHERE PID=100040
AND Date=''20081024''
'
WHERE
PID=100040 AND
Date='20081024'
EXECUTE sp_executesql @Query
答案 3 :(得分:0)
UPDATE CashBalances SET Balance1=0,Balance2=0 WHERE PID=258 AND
Date='20081024'
IF @@ROWCOUNT = 0
BEGIN
DECLARE @BalCode Char(1)
SET @BalCode = ISNULL((SELECT TOP 1 Balancecode
FROM CashBalances
WHERE Date=(SELECT MAX(Date) FROM CashBalances WHERE PID=258)),'I')
INSERT INTO CashBalances(PID,Date,BalanceCode,Balance1,Balance2,CCY)
VALUES (258 ,'20081024',@BalCode,0,0,' ')
END
--- @ teo van tok