How can i reproduce this procedure to CQL (Cassandra)? - sql

i have this procedure and now some how i need reproduce this procedure from SQL, to CQL, can you please help me? If Cassandra have same as procedures in SQL or not? And if not, how i can set variables for this?
CREATE PROCEDURE [dbo].[sp_DeleteOldTransactionLogs]
#p_daysback INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE
#r int
,#i int
,#maxLogId int
,#billion int = 1000000000
,#deleted int;
SET #r = 1;
SET #i = 1;
SET #deleted = 0;
SELECT
#maxLogId = MAX(ictransactionlogid)
FROM dbo.ictransactionLog WITH (INDEX(IX_ictransactionLog_time))
WHERE
time < DATEADD(day, #p_daysback, GETDATE());
WHILE #r > 0 AND #i <= 7
BEGIN
DELETE TOP (5000) -- this will change
dbo.ictransactionLog
WHERE ictransactionlogid <= #maxLogId;
SET #r = ##ROWCOUNT;
SET #deleted = #deleted + #r;
set #i = #i + 1;
END
SELECT #maxLogId = IDENT_CURRENT( 'ictransactionLog' );
IF #maxLogId > #billion
BEGIN
delete from ictransactionLog
where ictransactionlogid < 500000000
DBCC CHECKIDENT ('ictransactionLog', RESEED, 0);
END
SELECT #deleted;
END

No, it's not possible to do that in the CQL. There is only limited for user-defined functions & user-defined aggregates, and even they are quite limited.
You need to implement that as a code in some language, such as, Python, etc.

Related

Batch updates to SQL Table wont stop

I have a large table (18 million records) which I am updating using the following batch update snippet:
SET NOCOUNT ON;
DECLARE #rows INT, #count INT, #message VARCHAR(100);
SET #rows = 1;
SET #count = 0;
WHILE #rows > 0
BEGIN
BEGIN TRAN
UPDATE TOP 100000 tblName
SET col_name = 'xxxxxx'
SET #rows = ##ROWCOUNT
SET #COUNT = #count + #rows
RAISERROR ('count %d', 0, 1, #count) WITH NOWAIT
COMMIT TRAN
END
Even though the code has the #count increment logic, it races past the 18 million records I am trying to update. What am I missing here and what should I add/remove to make the updates stop at the 18,206,650 records that I have in the table?
Thanks,
RV.
Silly me. I was missing where clause on the update statement. Sorry y'all.

Cursorfetch error because of wrong variable type

i try to do a benchmark for SQL Statments for SQLServer.
I found a good benchmark loop online: https://github.com/jOOQ/jOOQ/blob/master/jOOQ-examples/Benchmarks/SQLServer/Benchmarking%20SQL%20Server%20(absolute).sql
DECLARE #ts DATETIME;
DECLARE #repeat INT = 10000;
DECLARE #r INT;
DECLARE #i INT;
DECLARE #dummy VARCHAR;
DECLARE #s1 CURSOR;
DECLARE #s2 CURSOR;
SET #r = 0;
WHILE #r < 5
BEGIN
SET #r = #r + 1
SET #s1 = CURSOR FOR
-- Paste statement 1 here
SELECT 1 x;
SET #s2 = CURSOR FOR
-- Paste statement 2 here
WITH t(v) AS (
SELECT 1
UNION ALL
SELECT v + 1 FROM t WHERE v < 10
)
SELECT * FROM t
SET #ts = current_timestamp;
SET #i = 0;
WHILE #i < #repeat
BEGIN
SET #i = #i + 1
OPEN #s1;
FETCH NEXT FROM #s1 INTO #dummy;
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM #s1 INTO #dummy;
END;
CLOSE #s1;
END;
DEALLOCATE #s1;
PRINT 'Run ' + CAST(#r AS VARCHAR) + ', Statement 1: ' + CAST(DATEDIFF(ms, #ts, current_timestamp) AS VARCHAR) + 'ms';
SET #ts = current_timestamp;
SET #i = 0;
WHILE #i < #repeat
BEGIN
SET #i = #i + 1
OPEN #s2;
FETCH NEXT FROM #s2 INTO #dummy;
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM #s2 INTO #dummy;
END;
CLOSE #s2;
END;
DEALLOCATE #s2;
PRINT 'Run ' + CAST(#r AS VARCHAR) + ', Statement 2: ' + CAST(DATEDIFF(ms, #ts, current_timestamp) AS VARCHAR) + 'ms';
END;
PRINT '';
PRINT 'Copyright Data Geekery GmbH';
PRINT 'https://www.jooq.org/benchmark';
This works great for when the statments i test only have one column they return. For example:
Select ID from Items Where ID=2;
But as soon as i try to select multiple rows like
Select * from Items Where ID=2;
i get the error:
Msg 16924, Level 16, State 1, Line 135 Cursorfetch: The number of
variables declared in the INTO list must match that of selected
columns.
So the column this concerns is
FETCH NEXT FROM #s1 INTO #dummy;
So as far as i understand the issue is that i try to fit to much columsn into the dummy variable. But how do i fix it? Im not so long working with SQL so any help would be appreciated.
That is not a useful or simple way to test queries.
It’s a lot of code so it’s not particularly easy, and uses a cursor to process the results so it includes the cost of processing the results on the server with a cursor, which is not present normally.
Normally you just run the query in SSMS and look at the Actual Execution Plan and perhaps the time and IO statistics, and perhaps the client statistics. The query results should be returned to the client, because that's what happens in production, and you should consider the time needed to transmit results over the network when benchmarking.
If you need to run a query without returning data to the client, you can use a pattern like
go
set statistics io on
set statistics time on
go
drop table if exists #foo;
with q as
(
select ...
from ...
)
select *
into #foo
from q
go 5
set statistics io off
set statistics time off
go

Insert query in while loop in a function

I need to write a SQL function that should return temp table with 2 columns. But I want to use while loop. I want to insert multiple insert queries to temp table.
But when I am using insert query in while loop in SQL function, it is giving the empty result. Following is my case.
Code something like this:
create function dbo.fn_GetSubTree1(#type as Varchar(50))
returns #tree table
(sizename Varchar(9) not null,shiptotal int)
as
BEGIN
Declare #maxsize int;
Declare #counter int=0;
WHILE #counter < 24
BEGIN
insert into #tree(sizename,shiptotal) select s.size,s.shp from style st join scale s on st.scale=s.scale and s.nrfkey='' and s.prepak=''
SET #counter = #counter + 1;
END
return
End
You have WHILE #counter < 24, but never initialise the counter to any value.
The line DECLARE #counter INT; doesn't initialise the variable to 0, it initialises it to NULL. Which means your first loop is checking NULL < 24 which isn't TRUE.
Try this...
Declare #counter int = 0;
...
WHILE #counter < 24
BEGIN
...
SET #counter = #counter + 1;
END
You also seem to have other issues, such as select ' + #Size + ','+#Shp + ' from ... making no apparent sense.
EDIT:
I recommend starting with making a simple case work and building it up from there. If it ever stops working, the problem is what ever you last changed.
CREATE FUNCTION dbo.fn_GetSubTree1(
#type AS NVARCHAR(50)
)
RETURNS #tree TABLE (
sizename NVARCHAR(9) NOT NULL,
shiptotal INT
)
AS
BEGIN
DECLARE #counter INT = 0;
WHILE (#counter < 24)
BEGIN
INSERT INTO
#tree(
sizename,
shiptotal
)
VALUES (
'Test',
#counter
)
SET #counter = #counter + 1;
END
RETURN
END

frequently DELETE in Stored Procedure

How I can create a stored procedure and use frequently query like this:
SET NOCOUNT ON;
DECLARE #r INT;
SET #r = 1;
WHILE #r > 0
BEGIN
BEGIN TRANSACTION;
DELETE TOP (100000)
dbo.table1
WHERE Create_Date < DATEADD(YEAR, -5, GETDATE());
SET #r = ##ROWCOUNT;
COMMIT TRANSACTION;
CHECKPOINT;
END
in my new stored procedure?
Thanks for Your answers.
You can make your DELETE statements dynamic using something like below:
CREATE PROCEDURE dbo.DeleteRows (
#tableName VARCHAR(50),
#timestampColName VARCHAR(100),
#since DATETIME2,
#rows INT = 100000
AS
BEGIN
SET NOCOUNT ON;
DECLARE #r INT;
SET #r = 1;
WHILE #r > 0
BEGIN
-- SQL injection might be a problem if table and column name are not coming from a trustworthy source (i.e. user input)
DECLARE #SQL = N'
DELETE TOP (' + CAST(#Count AS INT) + ')' + #tableName + '
WHERE ' + #timestampColName + ' < #since;'
EXEC sp_executesql #SQL, N'#since DATETIME', #since = #since
SET #r = ##ROWCOUNT;
END
END
SQL injection can be tackled using one of the techniques indicated in this question and its answers.

Database version

I have to write a procedure which is able using a Table version to bring the database to a specific moment in type. For instance to move from version 1 to version 10 or the other way around. The thing is I'm pretty blurry with this chapter, and the school course has almost nothing about it. I tried using the internet to build a solution but somehow I got stuck. Please help me understand what am I doing wrong.
Table version, 1 columnm, type int
query
create procedure [dbo].[goto_vs] (
#vs int
)
as
begin
declare #current_vs int, #counter int;
declare #sqlquery nvarchar(50); --query to modify
declare #sqlsp nvarchar(30);
declare #sqlversion nvarchar(3);
declare #sqlreverse nvarchar(10);
--get the current version from table
select #current_vs=version from dbo.version;
--checking for valid version
if (#current_vs = #vs) begin
print('The database is already at this version...')
return
end
else begin
if (#vs > 5) begin
print('Setting the version of databse to last one...')
set #vs = 5
end
else begin
if (#vs < 0) begin
print('Setting the database to default...')
set #vs = 0
end
end
end
--setting up the string for exec
set #sqlsp = 'exec sp_create_table_awards'
--check if we go further or earlier in time
print('Changing database version...')
if (#vs > #current_vs) begin
set #sqlreverse = ''
goto upgrading
end
else begin
set #sqlreverse = 'undo_create_awards'
goto downgrading
end
--upgrading code
upgrading:
set #counter = #current_vs + 1
while (#counter <= #vs) begin
set #sqlquery = #sqlsp + cast(#counter as nvarchar(2)) + #sqlreverse
print(#sqlquery)
exec sp_executeSql #sqlquery
set #counter = #counter + 1
end
goto ending
downgrading:
set #counter = #current_vs
while (#counter > #vs) begin
set #sqlquery = #sqlsp + cast(#counter as nvarchar(2)) + #sqlreverse
print(#sqlquery)
exec sp_executeSql #sqlquery
set #counter = #counter - 1
end
goto ending
ending:
update dbo.version set version=#vs
print('Database version changed...')
end
Considering I figured a way, and have got no responses, I will post it as a response because it may help other students which studie computer science
To simplify I named all my procedures by this pattern do_x and undo_x where x is a int where do / undo _x are procedures which pair toughter for example do_1 and undo_1 create a table and destroy a table
ALTER PROCEDURE [dbo].[goto_vs]
-- Add the parameters for the stored procedure here
#v int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare #i int
declare #toexec nvarchar(70)
set #i = (select version from version)
-- If the requested version is lower than the current one, downgrade.
while(#i > #v)
BEGIN
set #i = #i - 1
set #toexec = 'Undo_' + CONVERT(varchar,#i);
exec sp_executeSql #toexec
print #toexec
END
-- Otherwise, upgrade.
while(#i < #v)
BEGIN
set #toexec = 'Update_' + CONVERT(varchar, #i);
exec sp_executeSql #toexec
set #i = #i + 1
print #toexec
END
END