I need to pass this string parameter value via C# application to a SQL Server query:
'foo', 'bar'
This is the query in the code-behind:
sql = @String.Format(" SELECT * FROM ");
sql += String.Format(" [dbo].[PDTM] ");
sql += String.Format(" WHERE ");
sql += String.Format(" PDTM IN (@param1); ");
command.Parameters.AddWithValue("param1", txtPDTM.Text.ToString());
But this does not work yet because the output is empty.
Then I try to change the SQL query to:
sql = @String.Format(" SELECT * FROM ");
sql += String.Format(" [dbo].[PDTM] ");
sql += String.Format(" WHERE ");
sql += String.Format(" PDTM IN (" + txtPDTM.Text.ToString() + "); ");
And this works.
So what is the correct way to pass parameter to IN query in C#?
This is a function fn_split_string which splits a string:
ALTER function dbo.fn_split_string(@str nvarchar(1000),@sep nvarchar(1))
returns @tab_split table (id int identity(1,1),str nvarchar(1000) )
as
begin
declare @str1 as nvarchar(1000)
declare @istr as nvarchar(1000)
declare @i as integer
set @str1=@str
set @i=2
while @i>0
begin
set @i=charindex(@sep,@str1,1)
if @i>0
begin
set @istr=substring(@str1,1,@i-1)
insert into @tab_split(str) values(@istr)
set @str1=substring(@str1,@i+1,len(@str1))
end
end
insert into @tab_split(str) values(@str1)
return
end
And running the function as follows :
SELECT * FROM dbo.fn_split_string ('foo, bar',',');
The output is :
1 foo
2 bar
It would be something such as :
SELECT * FROM dbo.PDTM WHERE PDTM IN (SELECT str FROM dbo.fn_split_string(@param1,','))
As pointed already the next one is to pass directly a list of string to your SQL statement.
Hope this can help you.
Best regards,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.