在 SQL 声明语句中使用部分字符串

Use part of a string in SQL declare statement

我想进行一个查询,其结果与下面显示的结果相同,但我只需要在 SET 语句中插入前 4 位数字,即“Set $campaignNo = '0029'”是否有如何在这样的字符串语句中填写通配符?

declare @campaignNo varchar(60)
set @campaignNo = '0029_old_Leu_2021_1'

Select Count(PUR1.intTimestamp) AS #start
From [MicrobialScreening].[dbo].[PUR_IDs] as ID 
INNER JOIN [MicrobialScreening].[dbo].[PUR_Purification1] AS PUR1 
   ON id.intID=pur1.intID
where id.strCampaign = @campaignNo

也许LIKE就是你想要的:

declare @campaignNo varchar(60)
set @campaignNo = '0029'

Select Count(PUR1.intTimestamp) AS #start
From [MicrobialScreening].[dbo].[PUR_IDs] as ID 
INNER JOIN [MicrobialScreening].[dbo].[PUR_Purification1] AS PUR1 
   ON id.intID=pur1.intID
where id.strCampaign like @campaignNo+'%'

如果广告活动编号是固定宽度的(如初始问题中所述的前四个),则可以使用 LEFT 函数。

set @campaignNo = '0029'

...

where LEFT(id.strCampaign, 4) = @campaignNo

对于更复杂的解析,可以使用SUBSTRING or LIKE. If you are using an underscore to parse with LIKE, make sure you use the ESCAPE关键字来避免歧义。

where id.strCampaign = LIKE CONCAT(@campaignNo, '\_%') ESCAPE '\'