在做一個功能時,要求參數是動態傳入并且有參數可以動態傳出,字符串動態組成的sql以前只是知道 用Execute去執行,今 天發現sp_executesql這個是可以達成這個目 的。
ALTER PROCEDURE [dbo].[SLMFormateExportCenterFields]
-- Add the parameters for the stored procedure here
@TMP varchar(max),
@fields nvarchar(max) output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--DECLARE @TMP VARCHAR(MAX)
--SET @TMP = ‘sanow,orgFeeCode,orgName,FRCode,FRName,payDatetime,humanCategory,EmpCount,SSS47,SSS91,payYear,payMonth,orgSystemID,refno1,refno2,salaryType‘
DECLARE @sqlDy nvarchar(max)
SET @fields = ‘‘
SET @sqlDy = ‘
DECLARE @ITEMNO VARCHAR(20), @ITEMNAME VARCHAR(50)
DECLARE A CURSOR FOR
SELECT itemno, itemname FROM eHR3.dbo.E9SLMUploadCenterItems WHERE forexport = 1 ORDER BY sort1
OPEN A
FETCH NEXT FROM A
INTO @ITEMNO, @ITEMNAME
WHILE @@FETCH_STATUS = 0
BEGIN
IF CHARINDEX(@ITEMNO, @TMP,0) > 0
BEGIN
SET @fields = @fields + @ITEMNO + ‘‘ AS ‘‘ + ‘‘‘‘‘‘‘‘+ @ITEMNAME + ‘‘‘‘‘‘‘‘ + ‘‘,‘‘
END
FETCH NEXT FROM A
INTO @ITEMNO, @ITEMNAME
END
CLOSE A
DEALLOCATE A‘
exec sp_executesql @sqlDy, N‘@TMP varchar(max),@fields nvarchar(max) output‘, @TMP, @fields output
SET @fields = SUBSTRING(@fields,0, LEN(@fields))
RETURN
END
原文地址:https://www.cnblogs.com/sdikerdong/p/12176134.html