存储过程创建问题

时间:2012-03-07 23:43:36

标签: tsql stored-procedures

好的我对存储过程知之甚少,但是有谁知道我怎么能把它写成SP。我认为它有点到达但不完全。基本上我需要粘贴到我的查询中来创建它!:)

CREATE PROCEDURE sp_executesql
as
DECLARE
@cols AS NVARCHAR(MAX),
@y    AS INT,
@sql  AS NVARCHAR(MAX);

-- Construct the column list for the IN clause
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(w) AS [text()]
FROM (SELECT DISTINCT WeekNo AS W FROM dbo.Items) AS W
ORDER BY W
FOR XML PATH('')),
1, 1, N'');


-- Construct the full T-SQL statement
-- and execute dynamically
SET @sql = N'SELECT *
            FROM (SELECT ItemNo, WeekNo, Value
                    FROM dbo.Items) AS I
            PIVOT(SUM(Value) FOR WeekNo IN(' + @cols + N')) AS P;';

EXEC sp_executesql @sql;
GO

2 个答案:

答案 0 :(得分:0)

假设查询语句正确并且您只需要一个SP结构,它将是这样的:

创建程序SP_NAME @ variable1类型[输入/输出] 如 开始 --query 端

//执行SP EXEC SP_NAME'valueForVariable1'

希望这会有所帮助

答案 1 :(得分:0)

知道了。只是不要将名称证明为sp_executesql,将其命名为get_items或其他内容。

新程序:

CREATE PROCEDURE get_items

as
declare @cols AS NVARCHAR(MAX),
@y AS INT,
@sql AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT N',' + QUOTENAME(w) AS [text()]
FROM (SELECT DISTINCT week_no AS W FROM weekly_items) AS W
ORDER BY W
FOR XML PATH('')),1, 1, N'');

SET @sql = N'SELECT *
FROM (SELECT item_no, week_no, totval
FROM weekly_items) AS I
PIVOT(SUM(totval) FOR week_no IN(' + @cols + N')) AS P;';

EXEC sp_executesql @sql

GO