且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从数据库检索

更新时间:2023-02-03 23:34:04

请使用以下代码:

将单个参数的客户ID字符串发送到存储过程.然后在编写SP时使用以下方法:

Hi, use below code:

Send Customer ID String in single parameter to Stored Procedure. Then use below method when you writing SP:

Create procedure [dbo].[Get_Customer]
(
@strCustomerID varchar(5000)
)
As
Begin
Declare @x int, @i int
Declare @Cust_ID varchar(50)
Select *, ROW_NUMBER() OVER(ORDER BY (Select 0)) AS RowNumber into #Cust from dbo.split(@strCustomerID,',')

Select @x = COUNT(*) from #Cust
	while(@i<=@x)
	Begin
		Select @Cust_ID = items from #Cust where RowNumber = @i
SET @query='Select * from CustomerTable where CustomerID ='''+ @Cust_ID + ''''
print @query
		EXEC sp_executesql @query 
		------------------------------------
		
		Set @i = @i+1
	End


End


您可以创建用户定义的功能来分割客户ID,例如

You can create user defined function to split Customer IDs like this

CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000) -- List of delimited items
  , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))

BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO
--Test
select * from fnSplit('1,22,333,444,,5555,666', ',')
select * from fnSplit('1##22#333##444','##')  --note second item has embedded #
select * from fnSplit('1 22 333 444  5555 666', ' ')




您可以在存储过程中使用此功能.使用相同功能的示例代码片段如下所述




This function you can use in your Stored Procedure. sample code snippet for using the same function is as follows

select * from Customer_Master where CustomerId IN(SELECT * FROM	dbo.fnSplit(@CustomerId, ','))


其中 @CustomerId varchar 类型的参数.传递 @CustomerId 字符串的值时,可能类似于C00001,C00002,C00003 ...

希望这对您有所帮助.如果您需要进一步的帮助,请告诉我.
如果此方法正常,请接受解决方案.
谢谢


Where @CustomerId is parameter of type varchar. While passing the values of @CustomerId string can be like C00001,C00002,C00003...

I hope this will help you out. If you need further help please let me know.
If this works fine please accept the solution.
Thanks


根据您的存储过程,您不能这样做!
You can''t do that according to your stored procedure!
select * from Customer_Master where CustomerId IN(@CustomerId)


这与您想要的类似:
-您的str应该是:


This is similar what you want:
- Your str should be:

str="'C00001','C00002','C00003'";


-您的存储过程应为:


- Your stored procedure should be:

exec ('select * from Customer_Master where CustomerId IN(' + @CustomerId + ')')