Ich bin neueren SQL und ich habe mit Refactoring dieses Bit des Codes beauftragt. Wenn ich mir das anschaue, will ich mich übergeben.So fügen Sie eine Schleife zu einem SQL SELECT
Ich versuche, diese Sproc so zu ändern, dass sie eine beliebige Anzahl von Spalten statt einer festen Zahl zurückgeben kann. So sieht es jetzt aus.
ALTER PROCEDURE [frsuser].[usp_report_UnitFeatureHeaders]
AS
BEGIN
CREATE TABLE #features (SortOrder INT IDENTITY(1,1)
,label NVARCHAR(20) )
INSERT INTO #features (label)
SELECT label FROM UnitAttributeDefinition order by tab_sort_order
SELECT 'UnitID' AS UnitID
,'UnitName' AS UnitName
,'UnitAddress' AS UnitAddress
,'RateUnitType' AS RateUnitType
,'TaxDistrict' AS TaxDistrict
,'ContractType' AS ContractType
,'InactiveUnit' AS InactiveUnit
,(SELECT ISNULL(label,'') FROM #features WHERE SortOrder = 1) AS Feature01
,(SELECT ISNULL(label,'') FROM #features WHERE SortOrder = 2) AS Feature02
,(SELECT ISNULL(label,'') FROM #features WHERE SortOrder = 3) AS Feature03
,(SELECT ISNULL(label,'') FROM #features WHERE SortOrder = 4) AS Feature04
.......
,(SELECT ISNULL(label,'') FROM #features WHERE SortOrder = 100) AS Feature100
DROP TABLE #features
END
Hier ist die Idee von dem, wie ich es aussehen möchte.
ALTER PROCEDURE [frsuser].[usp_report_UnitFeatureHeaders]
@numberOfFeatures Int = 100
AS
BEGIN
CREATE TABLE #features (SortOrder INT IDENTITY(1,1)
,label NVARCHAR(20) )
INSERT INTO #features (label)
SELECT label FROM UnitAttributeDefinition order by tab_sort_order
DECLARE @counter INT = 0;
DECLARE @featureName NVARCHAR (20) = 'Feature';
SELECT 'UnitID' AS UnitID
,'UnitName' AS UnitName
,'UnitAddress' AS UnitAddress
,'RateUnitType' AS RateUnitType
,'TaxDistrict' AS TaxDistrict
,'ContractType' AS ContractType
,'InactiveUnit' AS InactiveUnit
(WHILE @counter < @numberOfFeatures
BEGIN
SET @featureName = 'Feature' + @counter;
(SELECT ISNULL(label,'') FROM #features WHERE SortOrder = @counter)
END
) AS @featureName
DROP TABLE #features
END
Ist eine solche refactor überhaupt möglich? und wenn ja, wie würde es aussehen?
Sie können dies nur mithilfe eines dynamischen SQL und STUFF für Ihre Feature-Spalten – maSTAShuFu
Immer wenn ich LOOP in einer SQL-Frage hören , Ich will mich übergeben. –