Double While Transac SQL Server 2008 - sql-server

I´m having some trouble about this query. The problem is that only one while is process, the firts one, don´t work for me.
This is my code:
The While #j, don´t work, but I don´t see the mistake ...
Thanks for your time.
CREATE PROCEDURE InsertVar
AS
DECLARE #i int
DECLARE #j int
SET NOCOUNT ON;
SET #i = 1
SET #j = 1
WHILE #j < 21
BEGIN
WHILE #i < 11
BEGIN
INSERT INTO Var(idline,idVar,CheckBox )
VALUES(#j,#i,0);
SET #i = #i + 1;
END;
SET #j = #j + 1;
END;
SELECT * FROM Var;
GO

There are other ways to do this logic (such as a single query). But your problem is that you do not re-initialize i inside the loop. Try this:
CREATE PROCEDURE InsertVar
AS
BEGIN
DECLARE #i int;
DECLARE #j int;
SET NOCOUNT ON;
SET #j = 1;
WHILE #j < 21
BEGIN
SET #i = 1;
WHILE #i < 11
BEGIN
INSERT INTO Var(idline, idVar, CheckBox)
VALUES(#j, #i, 0);
SET #i = #i + 1;
END;
SET #j = #j + 1;
END;
SELECT * FROM Var;
END;
GO

Use Recursive CTE to generate the rows. No need to use while loop or declaration of varaiables.
CREATE PROCEDURE Insertvar
AS
BEGIN
SET NOCOUNT ON;
;WITH cte
AS (SELECT 1 AS idline
UNION ALL
SELECT idline + 1 FROM cte
WHERE idline < 20),
cte1
AS (SELECT idline,1 AS idVar,0 AS CheckBox
FROM cte
UNION ALL
SELECT idline,idVar + 1,CheckBox FROM cte1
WHERE idVar < 10)
INSERT INTO [Var]
SELECT * FROM cte1
ORDER BY idline,idVar
SELECT * FROM [Var]
END

Related

MS SQL Server stored procedure won't complete [duplicate]

This question already has answers here:
Stored procedure hangs seemingly without explanation
(8 answers)
Closed 1 year ago.
I have this T-SQL that works just fine and it executes about 30 seconds.
DECLARE #BatchSize int = 1000,
#TransactionInterval tinyint = 5,
#MaxToDelete int = 10000,
#FactDeleted int = 0;
DECLARE #counter int = 1;
DECLARE #s datetime,
#e datetime,
#r int = 1;
SET #e = '20200606';
SELECT
#s = MIN(AtTime)
FROM
dbo.DevicePositions;
BEGIN TRANSACTION;
WHILE (#r > 0)
BEGIN
IF #r % #TransactionInterval = 1
BEGIN
COMMIT TRANSACTION;
BEGIN TRANSACTION;
END
DELETE TOP (#BatchSize)
FROM DevicePositions
WHERE AtTime >= #s
AND AtTime <= #e;
SET #FactDeleted = #FactDeleted + #BatchSize;
SET #r = ##ROWCOUNT;
SET #counter = #counter + 1;
IF #FactDeleted >= #MaxToDelete
BREAK;
END
IF ##TRANCOUNT > 0
BEGIN
COMMIT TRANSACTION;
IF #counter % 10 = 0 -- or maybe 100 or 1000
BEGIN CHECKPOINT;
END
END
GO
SELECT
A.Records
FROM
(SELECT
OBJECT_NAME(object_id) as ID,
SUM(row_count) AS Records
FROM
sys.dm_db_partition_stats
WHERE
object_id = OBJECT_ID('DevicePositions')
AND index_id < 2
GROUP BY
OBJECT_NAME(object_id)) A
I converted this code into a stored procedure and it won't complete so it runs forever.
The stored procedure:
ALTER PROCEDURE [dbo].[DeleteOldDevicePositions]
#MaxToDelete int , -- Max amount of records to delete
#BatchSize int , -- it is
#ToEndDate datetime -- Delete until this datetime
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TransactionInterval tinyint = 5, #FactDeleted int = 0;
DECLARE #counter int = 1;
DECLARE #s datetime, #e datetime, #r int = 1;
SELECT #s = MIN(AtTime) FROM dbo.DevicePositions;
BEGIN TRANSACTION;
WHILE (#r > 0)
BEGIN
IF #r % #TransactionInterval = 1
BEGIN
COMMIT TRANSACTION;
BEGIN TRANSACTION;
END
DELETE TOP (#BatchSize) FROM DevicePositions WHERE AtTime >= #s AND AtTime <= #ToEndDate;
SET #FactDeleted = #FactDeleted +#BatchSize;
SET #r = ##ROWCOUNT;
SET #counter = #counter + 1;
IF #FactDeleted >= #MaxToDelete
BREAK;
END
IF ##TRANCOUNT > 0
BEGIN
COMMIT TRANSACTION;
IF #counter % 10 = 0 -- or maybe 100 or 1000
BEGIN
CHECKPOINT;
END
END
SELECT A.Records FROM (
SELECT OBJECT_NAME(object_id) as ID, SUM(row_count) AS Records FROM sys.dm_db_partition_stats WHERE
object_id = OBJECT_ID('DevicePositions') AND index_id < 2
GROUP BY OBJECT_NAME(object_id) ) A
END
And I start it like
EXEC [dbo].[DeleteOldDevicePositions] 10000, 1000, '20200606'
So it starts and has no end.
What did I miss?
Thank you!
Thanks to Stored procedure hangs seemingly without explanation
I have used http://whoisactive.com/ to see that there is a rollback on that table.
So I used
exec sp_who
KILL 53 WITH STATUSONLY;
And see that have to wait until it will be done.
May be Parameter Sniffing is one of the reason for this Issue. Please have a look on the below Link.
https://blog.sqlauthority.com/2019/12/19/sql-server-parameter-sniffing-simplest-example/

I want to select data from a table, multiply it by different numbers, and put the total into a new table

I'm using SSMS, I have a sample table and I want to take each 'num' value (1, 2, 3) multiple it by a different number e.g. 1*1, 2*2, 3*3, and store the answer (14) in a new table.
I can create individual 'unnamed' tables, and I can create a new table with just one output, but not both.
DECLARE #myTableVariable TABLE (id INT, num int)
insert into #myTableVariable values(1,'1'),(2,'2'),(3,'3')
DECLARE #Multiplier INT
DECLARE #Counter INT
SET #Multiplier = 1
SET #Counter = 1
WHILE #Counter <=3
BEGIN
SELECT (num*#Multiplier) AS WMA FROM #myTableVariable WHERE ID = #Counter;
SET #Multiplier = #Multiplier + 1
SET #Counter = #Counter + 1
END
Create a variable and store the value in that variable. Doing this you are not creating any table.
Here is the code,
DECLARE #myTableVariable TABLE (id INT, num int)
insert into #myTableVariable values(1,'1'),(2,'2'),(3,'3')
DECLARE #Multiplier INT
DECLARE #Counter INT
SET #Multiplier = 1
SET #Counter = 1
DECLARE #total INT=0
WHILE #Counter <=3
BEGIN
--SELECT (num*#Multiplier) AS WMA FROM #myTableVariable WHERE ID = #Counter;
set #total = #total+(SELECT (num*#Multiplier) AS WMA FROM #myTableVariable WHERE ID = #Counter)
SET #Multiplier = #Multiplier + 1
SET #Counter = #Counter + 1
END
select #total
Hope this is what you are looking for...

Batch insert of data into a table

I have very big dataset about 40000000 items of data. I am trying to load this to a new table. Since the dataset is really big, I am trying to load them in batch so the log transaction would not be full. I am using the query below but still have issue with log transaction being full.
Is there a way to commit the transition after each batch so that it wont be saved in log and will go for next batch?
Please let me know if there is a way for me to solve this issue.
And SSIS is not an option for me currently.
DECLARE #I BIGINT;
DECLARE #icnt int;
DECLARE #n INT, #flag INT;
SELECT #icnt = (SELECT COUNT(*) FROM table1) A
PRINT #ICNT
BEGIN
SELECT #I = 0
WHILE #I <=#icnt
BEGIN
SELECT #n = 0
SELECT #flag = 1
BEGIN TRANSACTION
WHILE #flag != 0
BEGIN
;WITH A AS
(
SELECT
a.*,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS batchnum
FROM
table1
)
INSERT INTO table2 (*)
SELECT *
FROM A
WHERE batchnum >= #I AND batchnum <#I + 10000000
SELECT #I = #I + 10000000
SELECT #n = #n + 10000000
SELECT #flag = CASE WHEN #n >= 50000000 THEN 0
WHEN #I >= #icnt THEN 0 ELSE 1 END
PRINT #I
END
COMMIT TRANSACTION
END
END

select columns from a table within a cursor

For each item (actually a value, "ut" in the code) selected from the table #pub, I want to create some tables based on this "ut" value and then, if some criteria are satisfied, I will print this "ut". But there are some errors in my SQL Server code shown below.
select ut
into #pub
from wosclassification1813..clustering
where cluster_id1 = 145
DECLARE #temp_ut NVARCHAR(MAX);
DECLARE #citation_count INT;
DECLARE #dccp_count INT;
DECLARE #temp_string_1 NVARCHAR(MAX);
DECLARE #temp_string_2 NVARCHAR(MAX);
DECLARE #i INT;
SET #i = 1;
DECLARE #j INT;
SET #j = 0;
DECLARE #n INT;
SET #n = (select count(*) from #pub);
Declare Cur Cursor For select ut from #pub
Open Cur
Fetch next From Cur Into #temp_ut
WHILE #j < #n
Begin
SET #temp_string_1 = (CONVERT(NVARCHAR, #i))
EXEC('select s_ut as ut into #temp_string_1 from woskb.dbo.cwts_pairs where c_ut = #temp_ut')
SET #temp_string_2 = (CONVERT(NVARCHAR, #i))
EXEC('select a.c_ut as c_ut, a.s_ut as s_ut into temp_string_2 from woskb.dbo.cwts_pairs as a join #temp_string_1 as b on a.c_ut = b.ut join #temp_string_1 as c on a.s_ut = c.ut')
SET #dccp_count = (select count(*) from #dccp)
SET #citation_count = (select count(*) from #citing_pub)
SET #i = #i + 1
SET #j = #j + 1
if #dccp_count = #citation_count*(#citation_count-1)/2
print #temp_ut
Fetch Next From Cur Into #temp_ut
End
Close Cur
Deallocate Cur

Need to repeat the result rows based on a column value

I need a help in generating SQL result based on a column value to calculate per day amount.
I have a SQL like below.
select guid, reccharge, dayCareDaysCharged, dayCareHoursPerDay, RATE from tableA.
Here if reccharge = 0 (weekly) then the result should have 7 rows with RATE as RATE/7 for each row (per day amount);
if reccharge = 1 (monthly) then the result should have 30 rows with RATE as RATE/30 for each row;
if reccharge = 2 (yearly) then the result should have 365 rows with RATE as RATE/365 for each row;
if reccharge = 3 (hourly) then there should be a row as calculate it for a day;
How can I achieve this. Please help.
The question seems a little strange to me, but if I've followed it correctly then maybe this;
CREATE TABLE [#temp1] (reccharge tinyint,rdays smallint)
GO
declare #rcount smallint
set #rcount=0
while #rcount<7
begin
set #rcount=#rcount+1
insert #temp1 values (0,7)
end
set #rcount=0
while #rcount<30
begin
set #rcount=#rcount+1
insert #temp1 values (1,30)
end
set #rcount=0
while #rcount<365
begin
set #rcount=#rcount+1
insert #temp1 values (2,365)
end
insert #temp1 values (3,1)
GO
select t1.[guid], t1.reccharge, t1.dayCareDaysCharged, t1.dayCareHoursPerDay, t1.RATE/t2.rdays as RATE from tableA t1
inner join #temp1 t2 on t1.reccharge=t2.reccharge
order by t1.[guid]
I have not idea to do it in single query, but you can do it by using CURSOR as like below :
declare #reccharge int
declare #count int
declare #i int
declare #strSQL nvarchar(max) = 'select 1, 1 where 1 <> 1'
declare CurTest cursor for select reccharge from test
open CurTest
fetch next from CurTest into #reccharge
while ##fetch_status = 0
begin
set #i = 0;
select #count = case when #reccharge = 0 then 7 when #reccharge = 1 then 30 when #reccharge = 2 then 365 else 1 end
while #i < #count
begin
set #strSQL = #strSQL + ' union all select reccharge, Rate/' + cast(#count as varchar(10)) + ' from test where reccharge = ' + cast(#reccharge as varchar(10))
set #i = #i + 1;
end
fetch next from CurTest into #reccharge
end
close CurTest
deallocate CurTest
exec(#strSQL)

Resources