如果我想传递ID的列表/字符串,我应该在下面的StoredProc中定义我的数据类型。 (1,2,5,12,99)?
create PROCEDURE [dbo].[TABLE_Delete]
-- Add the parameters for the stored procedure here
@TId datatype = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
delete from dbo.TABLE T where T.Id in (@TId)
END
我的TId字段属于Int
答案 0 :(得分:0)
您需要将数据作为nvarchar(xx)
传递,例如' 1,2,3,4'
然后使用split函数拆分它们并将查询写为
delete from dbo.TABLE T where T.Id in (dbo.split(@param,','))
以下是分割功能的代码
CREATE FUNCTION Split
(
@delimited nvarchar(max),
@delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare @xml xml
set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'
insert into @t(val)
select
r.value('.','varchar(max)') as item
from @xml.nodes('//root/r') as records(r)
RETURN
END
GO
答案 1 :(得分:0)
分割的另一种方法
CREATE FUNCTION [dbo].[fnSplitString]
(
@string NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
WHILE @start < LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1
INSERT INTO @output (splitdata)
VALUES(SUBSTRING(@string, @start, @end - @start))
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END
RETURN
END