創建用戶定義的表類型和表來存儲你所期望的結果(例如我創建臨時表)和存儲過程,你需要
CREATE TABLE ##Result (
DeviceId INT,
DeviceParameter1FromSP INT,
DeviceParameter2FromSP INT
)
CREATE TYPE DeviceTbl AS TABLE(
DeviceId INT,
DeviceParameter1FromSP INT,
DeviceParameter2FromSP INT
)
IF OBJECT_ID('dbo.usp_DeviceOutPut') IS NOT NULL
BEGIN
DROP PROCEDURE dbo.usp_DeviceOutPut
END
CREATE PROCEDURE [dbo].[usp_DeviceOutPut]
(
@DeviceTbl AS DeviceTbl READONLY
)
As
BEGIN TRANSACTION;
BEGIN TRY
IF EXISTS (SELECT 1 From @DeviceTbl)
BEGIN
DECLARE @minid Int,@maxId INT,
@Sql NVARCHAR(MAX),
@DeviceParameter1FromSP INT,
@DeviceParameter2FromSP INT,
@DeviceId INT
SELECT @minid=MIN(DeviceId) From @DeviceTbl
SELECT @maxId=MAX(DeviceId) From @DeviceTbl
WHILE (@minid<[email protected])
BEGIN
INSERT INTO ##Result(
DeviceId,
DeviceParameter1FromSP,
DeviceParameter2FromSP
)
SELECT DeviceId,
DeviceParameter1FromSP ,
DeviceParameter2FromSP
FROM @DeviceTbl o WHERE NOT EXISTS (SELECT 1 From ##Result R Where R.DeviceId=o.DeviceId)--Duplicate records cnnot be inserted with this clause
AND [email protected]
SET @[email protected]+1
END
END
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
執行存儲過程與樣本數據
DECLARE @DeviceTbl AS DeviceTbl
INSERT INTO @DeviceTbl
SELECT 1,100,200 UNION ALL
SELECT 2,120,222
EXEC DBO.usp_DeviceOutPut @[email protected]
SELECT * FROM ##Result
輸出
Device DeviceParameter1FromSP DeviceParameter2FromSP
1 100 200
2 120 222
請張貼您的示例輸入日期。您可以對此方法使用數據透視功能。但要明確你的問題 –
@JimMacaulay:我發佈了樣本輸入數據。 – ckv
100,200,...等值如何?你如何生成它們? –