SQL - Combine results in whileloop - sql

i would like to get a single results using this code
DECLARE
#count INT = 1,
#cutoff DATETIME = '12/31/2015'
while #count < 30
begin
select COUNT(Accnumber) from table
where DATEDIFF(day,TranDateTime,#cutoff) <= 0
SET #count = #count + 1
end
EDIT: i already fix it. what i did was i add a variable for the table and insert into it and display the result. sorry for bad english :D
so,
DECLARE
#count INT = 1,
#cutoff DATETIME = '12/31/2015',
*#tbl table(result int)*
while #count < 30
begin
*insert into #tbl*
select COUNT(Accnumber) from table
where DATEDIFF(day,TranDateTime,#cutoff) <= 0
SET #count = #count + 1
end
*select * from #tbl*
im new here i don't know how to format answers correctly. again thanks for the response.

Related

SQL function - Split a number into part count

I want to split a number into parts(buckets).
For example when I split a number 13 by 4, expected output is 4 bucket (4,4,4,1)
13 split by 4 parts -> 4 (Expected output)
For example when I split a number 11 by 4, expected output is 3 bucket (4,4,3)
11 split by 4 parts -> 3 (Expected output)
For example when I split a number 3 by 4, expected output is 1 bucket
3 split by 4 parts -> 1 (Expected output)
How do I do this in SQL function
You Can use next Code for retrieving the buckets and the count:-
Declare
#InputNumber int,
#SplitBy int,
#Count int,
#Buckets VARCHAR(1000)
Set #InputNumber = 14
Set #SplitBy = 4
Set #Count = 0
While #InputNumber > #SplitBy
Begin
Set #Buckets = Convert(Varchar(10),#SplitBy) + ',' + isNULL( #Buckets,'')
Set #InputNumber = #InputNumber - #SplitBy
Set #Count = #Count + 1
End
Select #Buckets + Convert(Varchar(10),#InputNumber% #SplitBy) as Buckets , #Count + 1 as Count
Output:-
Buckets Count
4,4,4,2 4
You can try this way:
DECLARE #Number INT = 13, #Devided INT = 4, #Count INT = 0
WHILE (#Number >= #Devided)
BEGIN
set #Count = #Count + 1;
set #Number = #Number - #Devided
print #Devided
END
IF(#Number < #Devided)
BEGIN
Set #Count = #Count + 1;
print #Number
END
SELECT #Count
If you just want to count, you can try this way, demo on db<>fiddle
DECLARE #Number INT = 13, #Devided INT = 4, #Count INT
SET #Count = (#Number / #Devided)
IF(#Number % #Devided <> 0)
BEGIN
Set #Count = #Count + 1;
END
SELECT #Count
Hard to tell what exactly you're looking for, but using SQL functions only, here is one way. Try plugging in different numbers.
declare #num integer;
set #num=11;
select #num, concat(replicate('4,',floor(#num/4)),#num%4), floor(#num/4)+1;

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

SQL: how to check palindrome of a string without using reverse function?

I'm using SQL Server and I want to check whether the given string is a palindrome or not - but without using the reverse function.
There are multiple ways to achieve this. One of them is to check first and last character, slicing them if they're equal and continuing the process in a loop.
DECLARE #string NVARCHAR(100)
DECLARE #counter INT
SET #string = 'Your string'
SET #counter = LEN(#string)/2
WHILE (#counter > 0)
BEGIN
IF LEFT(#string,1) = RIGHT(#string,1)
BEGIN
SET #string = SUBSTRING(#string,2,len(#string)-2)
SET #counter = #counter - 1
END
ELSE
BEGIN
PRINT ('Given string is not a Palindrome')
BREAK
END
END
IF(#counter = 0)
PRINT ('Given string is a Palindrome')
A select without loops
DECLARE #Test VARCHAR(100)
SELECT #Test = 'qwerewq'
SELECT CASE WHEN LEFT(#Test, LEN(#Test)/2) =
(
SELECT '' + SUBSTRING(RIGHT(#Test, LEN(#Test)/2), number, 1)
FROM master.dbo.spt_values
WHERE type='P' AND number BETWEEN 1 AND LEN(#Test)/2
ORDER BY number DESC
FOR XML PATH('')
)
THEN 1
ELSE 0
END
Here's an example using LEFT and RIGHT. I use the #count variable to change position, then grab the left-most and right-most char:
DECLARE #mystring varchar(100) = 'redivider'
DECLARE #count int = 1
WHILE (#count < LEN(#mystring) / 2) AND #count <> 0
BEGIN
IF (RIGHT(LEFT(#mystring, #count), 1) <> LEFT(RIGHT(#mystring, #count), 1))
SET #count = 0
ELSE SET #count += 1
END
SELECT CASE WHEN #count = 0
THEN 'Not a Palindrome'
ELSE 'Palindrome'
END [Result]

Can't understand why i'm getting an incorrect syntax error in my script?

Can anyone tell me why I'm getting an incorrect syntax error for the line
SELECT * INTO #pre_and_post_op FROM NBOCAP(#StartDate,#EndDate,#OrgCode)
Code:
DECLARE #StartDate datetime
DECLARE #EndDate datetime
DECLARE #OrgCodeString varchar (8000)
SET #StartDate = '01-JAN-11'
SET #EndDate = '31-MAR-14'
SET #OrgCodeString = 'RA720|RQ801|RVJ20|RN325|8AAAA|RBA11'
DECLARE #i int
DECLARE #OrgCode varchar(10)
DECLARE #OrgCount int
DECLARE #TrustTable TABLE
(idx int IDENTITY(1,1), org varchar(10))
DECLARE #pre_and_post_op TABLE
(CARE_ID int,ERR_NumberOfNodesPositive int,ERR_FinalPathologyTCategory int,
ERR_FinalPathologyNCategory int,ERR_FinalMCategory int)
INSERT INTO #TrustTable
SELECT * FROM SplitString(#OrgCodeString, '|')
SET #i = 1
SET #OrgCount = (SELECT COUNT(*) FROM #TrustTable)
IF #OrgCount > 0
WHILE (#i <= #OrgCount)
BEGIN
SET #OrgCode = (SELECT org FROM #TrustTable WHERE idx = #i)
SELECT * INTO #pre_and_post_op FROM NBOCAP(#StartDate,#EndDate,#OrgCode)
SET #i = #i + 1
END
You cannot SELECT INTO a table variable. To quote MSDN:
You cannot specify a table variable or table-valued parameter as the new table.
Use INSERT INTO ... SELECT instead
INSERT INTO #pre_and_post_op SELECT * FROM NBOCAP(#StartDate,#EndDate,#OrgCode)

How to check upper case existence length in a string - Sql Query

How to check upper case existence length in a string using Sql Query?
For Eg:
1.KKart - from this string the result should be 2, because it has 2 upper case letters.
2.WPOaaa - from this string the result should be 3, because it has 3 upper case letters.
Thanks in advance
There is no built-in T-SQL function for that.
You can use a user-defined function like this one:
CREATE FUNCTION CountUpperCase
(
#input nvarchar(50)
)
RETURNS int
AS
BEGIN
declare #len int
declare #i int
declare #count int
declare #ascii int
set #len = len(#input)
set #i = 1
set #count = 0
while #i <= #len
begin
set #ascii = ascii(substring(#input, #i, 1))
if #ascii >= 65 and #ascii <= 90
begin
set #count = #count +1
end
set #i = #i + 1
end
return #count
END
Usage (with the examples from your question):
select dbo.CountUpperCase('KKart') returns 2.
select dbo.CountUpperCase('WPOaaa') returns 3.
How about something like this :
SELECT len(replace(my_string_field,'abcdefghijklmnopqrstuvwxyz','')) as 'UpperLen'
FROM my_table
The principle is simply to replace all lower case char by nothing and counts the remaining.