问题
I have a Table shown below
DateRange
10/1
11/1
12/1
I am looping through this table using cursor and trying to populate a temp table
Create table #BidStatusCalculation1
(
Code nvarchar(max),
Data int
)
Declare @monthStart varchar(20)
DECLARE cur CURSOR FOR SELECT DateRange FROM @dateRange
OPEN cur
FETCH NEXT FROM cur INTO @monthStart
WHILE @@FETCH_STATUS = 0 BEGIN
Insert into #BidStatusCalculation1
select 'SL Payroll',Count(*) from DashboardData
where DataType = 'Bid'
and CONVERT(NVARCHAR, CreatedDate, 105) = convert(datetime,
(@monthStart+'/'+@RequestYear))
FETCH NEXT FROM cur INTO @monthStart
END
CLOSE cur
DEALLOCATE cur
This gives me a result like below
Code Data
SL Payroll 22
SL Payroll 33
SL Payroll 43
I am looking to modify the table So I get just one row like
Code Data1 Data2 Data3
SL Payroll 22 33 43
Can someone please tell me what a good approach might be to first Insert Data inside a table on the first loop and then update it. I can put a variable to count the loop iteration and then write separate insert and update but was wondering if there is a better way.
Thanks
回答1:
Use PIVOT as
SELECT Code,
[22] Data1,
[33] Data2,
[43] Data3
FROM
(
SELECT *
FROM T
) TBL
PIVOT
(
MAX(Data) FOR Data IN([22],[33],[43])
) PVT
Demo
For dynamic pivot
CREATE TABLE T
(
Code VARCHAR(45),
Data INT
);
INSERT INTO T VALUES
('SL Payroll', 22),
('SL Payroll', 33),
('SL Payroll', 43);
DECLARE @IN VARCHAR(MAX) = '',
@Cols VARCHAR(MAX) = '';
SELECT @IN = @IN + ',' + QUOTENAME(Data),
@Cols = @Cols + ',' + QUOTENAME(Data) + ' AS Data'+
CAST(ROW_NUMBER()OVER(ORDER BY (SELECT NULL)) AS VARCHAR)
FROM T;
SELECT @IN = STUFF(@IN, 1, 1, ''), @Cols = STUFF(@Cols, 1, 1, '');
DECLARE @SQL NVARCHAR(MAX) = N'SELECT Code, ' +
@Cols+
' FROM (SELECT * FROM T) TBL PIVOT (MAX(Data) FOR Data IN('+
@IN+
')) PVT';
EXECUTE sp_executesql @SQL;
Demo
来源:https://stackoverflow.com/questions/54134488/insert-and-update-in-a-cursor-in-sql-server