[英]T-SQL Querying a table using a variable
I have been tasked with updating a stored procedure and I'm trying to figure out the most efficient way of performing the select. 我的任务是更新存储过程,我试图找出执行选择的最有效方法。 Here is the current code, vaultID
and clientID
are input parameters: 这是当前代码, vaultID
和clientID
是输入参数:
SELECT
@siteID = Site.siteID,
@siteGroupID = Site.siteGroupID,
@customerID = Customer.customerID
FROM
Customer
INNER JOIN
Site ON Customer.siteID = Site.siteID
WHERE
Site.phoneNumberIVR = @vaultID
AND Site.production = 1
AND Customer.clientID = @clientID
The update I'm working on has to do with the @clientID
variable. 我正在处理的更新与@clientID
变量有关。 If a record has a specific @siteGroupID
, the clientID
needs to be passed in as it was received. 如果记录具有特定的@siteGroupID
,则必须在接收到该@siteGroupID
传递该clientID
。 If the record has a different type of @siteGroupID
, the @clientID
variable needs to be appended with a specific prefix. 如果记录的@siteGroupID
类型不同,则@clientID
变量需要附加特定的前缀。 That prefix is also going to be stored on the site table. 该前缀也将存储在站点表中。
I realize I can make a call to the site table initially to get the prefix, and then modify the @clientID
variable, but I'm trying to figure out if there is a way to do this with just one call. 我意识到我可以先调用site表来获取前缀,然后修改@clientID
变量,但是我试图找出是否有一种方法可以仅通过一次调用来实现。 I've been trying different case statements but I'm not sure this is even feasible. 我一直在尝试不同的案例陈述,但是我不确定这是否可行。
If I understand your issue correctly, then you should be able to throw a CASE
in your SELECT
with your condition to do the appending: 如果我正确地理解了您的问题,那么您应该可以根据CASE
在SELECT
抛出一个CASE
来进行追加:
SELECT
@siteID = Site.siteID,
@siteGroupID = Site.siteGroupID,
@customerID = Customer.customerID,
@clientID =
CASE
WHEN Site.siteGroupID = 1234 THEN Site.Prefix + @clientID
ELSE @clientID
END
FROM
Customer
inner join Site on Customer.siteID = Site.siteID
WHERE
Site.phoneNumberIVR = @vaultID
and Site.production = 1
and Customer.clientID = @clientID
Of course, depending on the datatypes of @clientID
and Site.Prefix
, you might have to do something other than a simple +
to do the appending. 当然,根据@clientID
和Site.Prefix
的数据类型,您可能需要执行除简单+
之外的其他操作来进行附加。 For example if both were integer
datatypes, you can append then with some CONVERT
calls: 例如,如果两个都是integer
数据类型,则可以追加一些CONVERT
调用:
@clientID = CONVERT(integer, CONVERT(varchar, Site.Prefix) + CONVERT(varchar, @clientID))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.