[英]How to create Dynamic SQL Query
I have int[] ids and i want to create an sql statement where i have to get all the details of theuser where user_id in (int[]).I am using prepared statement , so please help me with this. 我有int [] id,我想创建一个sql语句,我必须在(int [])中获取user_id所在的用户的所有详细信息。我正在使用准备好的语句,所以请为此提供帮助。
SELECT * FROM userrequest WHERE USER_ID IN ?
Now the problem is what to set in the parameter.There is nothing as pstmt.setintarray. 现在的问题是在参数中设置什么。pstmt.setintarray没有任何东西。
One solution ( of not using dynamic sql , Assuming you're using MSSQL SERVER) : 一种解决方案(不使用动态sql,假设您使用的是MSSQL SERVER):
Assuming you send a CSV string of values : 假设您发送的是CSV字符串值:
'1,2,3,4'
You can do : 你可以做 :
SELECT * FROM userrequest WHERE USER_ID IN (SELECT Element from dbo.FN_Split('1,2,3,4',','))
Where FN_Split is : 其中FN_Split是:
CREATE FUNCTION [dbo].[FN_Split]
(
@InDelimitedString varchar(max),
@InDelimiter varchar(10)
)
RETURNS
@tblArray TABLE
(
ElementID smallint IDENTITY(1,1),
Element varchar(1000)
)
AS
BEGIN
DECLARE @StrPos smallint,
@StrStart smallint,
@DelimiterLength smallint
SET @DelimiterLength = LEN(@InDelimiter)
--loop through source string and add elements to destination table array
WHILE LEN(@InDelimitedString) > 0
BEGIN
SET @StrPos = CHARINDEX (@InDelimiter, @InDelimitedString)
IF @StrPos = 0
BEGIN
INSERT INTO @tblArray VALUES(@InDelimitedString)
BREAK
END
ELSE
BEGIN
INSERT INTO @tblArray VALUES(SUBSTRING(@InDelimitedString, 1,@StrPos - 1))
SET @StrStart = @StrPos + @DelimiterLength
-- Shift source string left
SET @InDelimitedString = SUBSTRING(@InDelimitedString, @StrStart , LEN(@InDelimitedString) - @StrStart + 1)
END
END
RETURN
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.