如何在不使用更新语句的情况下在标志中插入值

How to insert value in flag without using update statement

我使用下面的查询在 table 中插入数据,最后使用更新语句更新标志。我可以在不使用更新语句的情况下插入值吗?

更新语句取决于 count_polls 和 total_count 的值,如果它们相等则标志应为 1,否则为 0

Declare @batchid varchar(4000)
set @batchid = (select batch id from polls_batch)
INSERT INTO [dbo]. [FeedSummary_test] (count_polls, total_count, BatchId, FeedLogStatus)

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_1] where batchid = @batchid

union

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_2] where batchid = @Batchid

Union

SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_3] where batchid = @batchid

update [dbo].[FeedSummary_test]
set Flag = IIF(count_polls=total_count,1,0)

我从 SSIS 中的变量中得到这些问号,结果应该是这样的:

这些问号的查询是这样的:

select(select count(*) from dbo.AR_Feed_one) count_1,
(select count(*) from dbo.AR_Feed_two) count_2,
(select count(*) from dbo.AR_Feed_three )count_3

然后我将这些值存储在变量中并使用 ?.

将它们插入到查询中
Final table should look like this
Count_polls,    TotalCount,     BatchID,    FeedLogStatus.  Flag
100 100 BUF 0   1
200 200 BUF 0   1
150 120 BUF 0   0

对于特定的 batchId,将有三行具有不同的总计数和计数轮询。

您可以将初始 select 添加到通用 table 表达式中,这样您就可以在插入中使用结果:

Declare @batchid varchar(4000)
set @batchid = (select batch id from polls_batch)

;WITH cte AS (
  SELECT COUNT(*) AS count_polls, ? AS total_count, 0 AS BatchId, 0 AS FeedLogStatus FROM [dbo].[PollsFeed_1] where batchid = @batchid
  
  UNION
  
  SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_2] where batchid = @Batchid
  
  UNION
  
  SELECT COUNT(*), ?, 0, 0 FROM [dbo].[PollsFeed_3] where batchid = @batchid
)
INSERT INTO [dbo]. [FeedSummary_test] (count_polls, total_count, BatchId, FeedLogStatus, Flag )
SELECT count_polls, total_count, BatchId, FeedLogStatus, IIF(count_polls=total_count,1,0)
FROM cte