我有多个具有单一识别码的客户端和 2 个具有多个标识符的客户端。我试图找到一种好方法,将客户端代码用作 where 子句中单个和多个代码的存储过程的参数。
我目前有一个变量,它接受输入的参数并将其转换为单个字符(客户端代码),但使用带有“in”的变量不起作用。我还尝试将客户端代码格式化为 where 子句中的 case 表达式,但无法弄清楚它的格式。
ALTER PROCEDURE [dbo].[client_tonnage] @input varchar(100)
as
select input =
case
when @input = 'client1' then 'C1'
when @input = 'client2' then '''C2'', ''C3'', ''C4'''
if object_id('tempdb..#temp_table') is not null drop table #temp_table
insert into #temp_table (date_time, clientid, ACTUAL_WEIGHT)
from Log
where clientid in (@input)
select * from #temp_table
我希望能够包含具有多个客户端代码的客户端,但上述格式不起作用。任何解决方法将不胜感激!
如果要保存多个值,请使用表变量:
ALTER PROCEDURE [dbo].[client_tonnage] @input varchar(100)
as
BEGIN
DECLARE @ClientIDs TABLE (ClientID VARCHAR(10))
IF @input = 'client1'
INSERT INTO @ClientIDs (ClientID) VALUES ('C1')
ELSE IF @input = 'client2'
INSERT INTO @ClientIDs (ClientID) VALUES ('C2'),('C3'),('C4')
if object_id('tempdb..#temp_table') is not null
drop table #temp_table
insert into #temp_table (date_time, clientid, ACTUAL_WEIGHT)
SELECT
-- The proper columns
from
Log AS L
INNER JOIN @ClientIDs AS C ON L.clientid = C.ClientID
select * from #temp_table
END
尽管您对输入和客户端 ID 之间的“映射”进行了硬编码。更好的方法是将此关系存储在物理表中:
CREATE TABLE ClientMappings (
ClientID VARCHAR(10) PRIMARY KEY,
ClientCode VARCHAR(10))
INSERT INTO ClientMappings (
ClientID,
ClientCode)
VALUES
('C1', 'client1'),
('C2', 'client2'),
('C3', 'client2'),
('C4', 'client2')
所以你用一个简单的连接来解决这个问题:
ALTER PROCEDURE [dbo].[client_tonnage] @input varchar(100)
as
BEGIN
if object_id('tempdb..#temp_table') is not null
drop table #temp_table
insert into #temp_table (date_time, clientid, ACTUAL_WEIGHT)
SELECT
-- The proper columns
from
Log AS L
INNER JOIN ClientMappings AS C ON L.clientid = C.ClientID
WHERE
C.clientcode = @input
select * from #temp_table
END
此外,如果您的 SP只是选择此数据,则不需要临时表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句