SQL Query To Find Proceeding Records - sql

This is a hard question for me to verbalize. I'll do my best. This is my record set:
DealershipID PlacementDealershipID
40309 -1
787289 40309
787461 787289
787402 787461
787520 787402
You will notice that the top of the chain is ID 40309 that has a PlacementDealershipID of -1. If we start with ID 787520, the PlacementDealershipID goes "up" the chain, until we get to DealershipID 40309.
Desired results would look like this starting at DealershipID 787520.
Starting DealershipID ---->>> 787520
1 Level(s) Up ---->>> 787402
2 Level(s) Up ---->>> 787461
3 Level(s) Up ---->>> 787289
4 Level(s) Up ---->>> 40309
I want to print a list of DealershipID's in SQL in order of DealershipID from starting point to 40309. I have done this using a while loop and declared variables. (Code Below). Is there an easier way to do this with SQL built in functionality?
-- Loop and pull structure
set #PreceedingDealershipID = 999
set #LevelNumber = 1
set #ContinueLoop = 1
set #LoopCount = 0
-- Determin maximum level for this system
set #MaxLevel = 30
set #MaxLevel = coalesce(#MaxLevel,30)
PRINT N'Starting ID ---->>> ' + convert(varchar(40), #DealershipID);
while (#ContinueLoop = 1 and #PreceedingDealershipID <> -1 and #PreceedingDealershipID <> 0)
begin
set #LoopCount = #LoopCount + 1
if (#LoopCount > #MaxLevel)
begin
raiserror('THERE IS A LOOP IN THE DATABASE! CANNOT CONTINUE!',15,15)
return
end
SELECT #PreceedingDealershipID = d.PlacementDealershipID
FROM Sponsorship as d WITH (NOLOCK)
WHERE d.DealershipID = CASE WHEN #LevelNumber = 1 THEN #DealershipId ELSE #PreceedingDealershipID END
if (#PreceedingDealershipID <> 0 and #PreceedingDealershipID <> -1)
Begin
PRINT N'Level ' + convert(varchar(40), #LevelNumber) + ' Next Level Up ---->>> ' + convert(varchar(40), #PreceedingDealershipID);
set #LevelNumber = #LevelNumber + 1
End
end -- end main loop

Related

SQL Binomial Distribution/Arithmetical Overflow

I created a function for a cumulative binomial distribution. It works well for extremely modest sample sizes, but I get a arithmetical overflow on larger samples.
The largest culprit is the n!. In excel 170! = 7.3E+306. 171! = #NUM!
Excel has an internal function that calculates binomial distribution, and it works with ns much, much larger than 170.
Is there something I can do to limit the magnitude of the #s generated?
EDIT: I played with this
SET #probout = 2*3*4*5*6*7*8*9*10*11*12
Worked fine
SET #probout = 2*3*4*5*6*7*8*9*10*11*12*13/10000
Resulted in overflow
Function below.
ALTER FUNCTION [dbo].[binomdist_cumulative]
(
#n int
,#k int
,#p float
)
RETURNS float
AS
BEGIN
-- Local Variable Declarations
-- ---------------------------
DECLARE #kfac float
,#nfac float
,#nkfac float
,#i float
,#f int
,#probout float
SET #i = 0
SET #f = 0
SET #nfac = 0
SET #kfac = 0
SET #nkfac = 0
SET #probout = 0
WHILE #i <= #k
BEGIN
--k!
SET #f = #i-1
SET #kfac = #i
IF #kfac > 0
BEGIN
WHILE #f > 0
BEGIN
SET #kfac = #kfac*#f
SET #f = #f -1
END
END
ELSE
BEGIN
SET #kfac = 1
END
--n!
SET #f = #n-1
SET #nfac = #n
IF #nfac > 0
BEGIN
WHILE #f > 0
BEGIN
SET #nfac = #nfac * #f
SET #f = #f -1
END
END
ELSE
BEGIN
SET #nfac = 1
END
--(n-k)!
SET #f = #n-#i-1
SET #nkfac = #n-#i
IF #nkfac > 0
BEGIN
WHILE #f > 0
BEGIN
SET #nkfac = #nkfac * #f
SET #f = #f -1
END
END
ELSE
BEGIN
SET #nkfac = 1
END
--Accumulate distribution
SET #probout = #probout + #nfac/(#kfac*#nkfac)*POWER(#p,#i)*POWER(1-#p,#n-#i)
SET #i = #i+1
END
RETURN #probout
END
Let me give you a hint.
If you calculate the full factorials, you are quickly going to get overflows. If you do an incremental calculation, the you won't.
For instance, instead of calculating (5 // 3) as (5*4*3*2*1) / ((3*2) * (3*2*1)), calculate it as: (5 / 3) * (4 / 2) * (3 / 3) * (2 / 2) * (1 / 1). . . oh, wait, you can see that the last three terms are all "1".
To be clear, you want to calculate the product of:
((n - i) / (n - k - i)
For i between 0 and k - 1. That is, you are dividing the product of k consecutive numbers ending in n with k consecutive numbers starting with 1.
You'll see that this incremental approach will forestall the issues with overflow.

Iterate through each string and its every character and make string using SQL?

I am making pattern for my strings in database here is my needs:
I have to iterate through each record and then I have to check its every character of string using SQL
After that I have to concatenate the string and show like that:
//DECLARING STRINGS IN VARIABLES
SET #str = '4444--6699p'
SET #CHS = '%[a-z]'
SET #CHE = '[a-z]'
SET #CHE2 = '[a-z]%'
SET #NUMS = '%[0-9]'
SET #NUME = '[0-9]'
SET #NUME2 = '[0-9]%'
SET #CHR = '-'
//GET THE IDENT OF SLASH
SET #INDENT = (SELECT PATINDEX('%-%', #str));
// CHECH CONTAIN CHARECTER OR NOT
IF PATINDEX('%[a-z]%' , #str) > 0
//BUILT STRING TILL INDENT
SET #CHA = #CHS
while #id <= #INDENT
begin
set #id = #id + 1
SET #CHA = #CHA + #CHE
end
SET #CHA = #CHA + #CHE2
print #CHA
end
//IF NO CHARECTER BUILT HERE
ELSE
print #NUMS + #NUME + #NUME2
but no want to concate string in that this is a pattern but here is explaination
have a look at database strings now
// DATABASE EXAMPLES OF STRING
(512) 482-2392
(518) 457-5181
http://www.menupages.com/restaurants/cafe-shane/
https://www.google.com/#q=auto
025-121-3453
429–432–2145
there expression returned as for 1 if record exist 3 times or more other wise null
(%[0-9][0-9][0-9]%) [0-9][0-9][0-9] - [0-9][0-9][0-9][0-9]
expressions can be like that abcz-aaassss-ccv so [a-z]{0,3}-[a-z]{0,10}-[a-z]{0,3}
HINT:
As in case of c sharp we do
string builtme;
builtme = builtme + builtme;
ACHEIVEMENT
HERE IS OUT PUT EXAMPLE
%[a-z][a-z][a-z]% - %[a-z][a-z][a-z][a-z]%-%[a-z][a-z][a-z]%

VBA - Check if recordset has been deleted before updating DB

I'm experimenting with VBA and i made the following thingy.
Dim rs1 As Recordset
Set rs1 = CurrentDb.OpenRecordset("TBL_Registratie")
With rs1
.AddNew
!leerling_Id = Me.leerling_Id
datum = DateValue(!datum_tijd)
tijd = TimeValue(!datum_tijd)
weekDag = Weekday(datum, vbMonday)
Select Case weekDag
Case 1, 2, 4
Select Case tijd
Case "07:00:00" To "08:00:00"
!score = !score + 1
Case "16:00" To "16:30"
!score = !score + 1
Case "16:31" To "17:00"
!score = !score + 2
Case "17:01" To "22:00"
!score = !score + 3
Case Else
Me.txt_resultaat.Caption = "Het is geen opvang"
Me.txt_resultaat.Visible = True
( rs1.close ? )
End Select
other cases
.Update
.Close
QUESTION: How can i check if my last record in there recordset has a score added or not? if not, i want to delete it and close Else Update & Close
A much easier way: Calculate the score before adding the record, save all needed data in variables instead of recordset fields.
Then only if score > 0 do the rs1.AddNew etc.

Nesting while loop inside a while loop in cshell

I need my code to read files that are numbered between 1 and 4000. It will then do something with the files, I am trying to break them up in blocks of 500 with the following.
#!/bin/tcsh
# x = 1
# looper = 1
while ($x < 3)
while ($looper < 500)
#filenumber = $x -1
#filenumber = $filenumber * 500
#filenumber = $filenumber + $looper
echo $filenumber
#looper += 1
done
#x += 1
done
I want this to count from 1 to 1000 in units of 500. However when I try this the script only counts to 500. Does anyone know why this is?
Thanks for your help
You need to initialize #looper = 1 inside the outer loop, otherwise it gets initialized only once, and starts the second iteration with the value 500.
# x = 1
while ($x < 3)
#looper = 1 <-- here
while ($looper < 500)
#filenumber = $x -1
#filenumber = $filenumber * 500
#filenumber = $filenumber + $looper
echo $filenumber
#looper += 1
done
#x += 1
done
The answer is that right beneath the #x +=1 line there needs to be a line resetting the $looper variable
#x += 1
#looper = 1
done
WHOOPS!!!

VB.NET nested for loops

I am having two datasets,I have to check if plant code is 1st dataset and 2nd dataset then i have to set some value for a variable.If plant code is in 1st dataset and not in second dataset then have to set some value.I have try this with following code,but i m not getting output as i want
If Not dsCheckForBOM Is Nothing AndAlso dsCheckForBOM.Tables.Count > 0 Then
If dsCheckForBOM.Tables(0).Rows.Count > 0 Then
For count1 As Int32 = 0 To dsCheckForBOM.Tables(0).Rows.Count - 1
For count2 As Int32 = 0 To dsTmpMat.Tables(0).Rows.Count - 1
If dsTmpMat.Tables(0).Rows(count2)("PLANT_CODE").ToString() = dsCheckForBOM.Tables(0).Rows(count1)("PLANT_CODE").ToString() Then
dsTmpMat.Tables(0).Rows(count2)("BOM_IND") = 1
dsTmpMat.Tables(0).Rows(count2)("BOM_DESC") = "BOM CREATED"
If count2 < dsTmpMat.Tables(0).Rows.Count - 1 AndAlso count1 < dsCheckForBOM.Tables(0).Rows.Count - 1 Then
count2 = count2 + 1
count1 = count1 + 1
End If
Else
dsTmpMat.Tables(0).Rows(count2)("BOM_IND") = 0
dsTmpMat.Tables(0).Rows(count2)("BOM_DESC") = "BOM NOT CREATED"
If count2 < dsTmpMat.Tables(0).Rows.Count - 1 Then
count2 = count2 + 1
End If
End If
Next
Next
Else
For i As Int32 = 0 To dsTmpMat.Tables(0).Rows.Count - 1
dsTmpMat.Tables(0).Rows(i)("BOM_IND") = 0
dsTmpMat.Tables(0).Rows(i)("BOM_DESC") = "BOM NOT CREATED"
Next
End If
End If
I can't test this, but I think you need to use a different approach.
First, there is no need to have two loop nested. Use the Select method to find the rows in the temporary table.
Second, if you don't find the row in the temporary table then I think you need to create it, not to set the last row of the temporary table to zero
If Not dsCheckForBOM Is Nothing AndAlso dsCheckForBOM.Tables.Count > 0 Then
' To remove the clutter, assign the two tables
' to two local variables and work with them
Dim tempTable = dsTmpMat.Tables(0)
Dim checkTable = dsCheckForBOM.Tables(0)
If checkTable.Rows.Count > 0 Then
' Loop on the primary table
For count1 As Int32 = 0 To checkTable.Rows.Count - 1
' Get the key to search for in the temporary table
Dim plantCode = checkTable.Rows(count1)("PLANT_CODE").ToString()
' Use Select to return an array of rows that match the condition.
' I suppose that PLANT_CODE is a primary key value here, so just one
' row should be returned
Dim foundRows = tempTable.Select("PLANT_CODE = '" plantCode + "'")
if foundRows.Count > 0
foundRows(0)("BOM_IND") = 1
foundRows(0)("BOM_DESC") = "BOM CREATED"
Else
' No row found, so create a new row and add it to the temporary table
Dim newRow = tempTable.NewRow()
newRow("BOM_IND") = 0
newRow("BOM_DESC") = "BOM NOT CREATED"
tempTable.Rows.Add(newRow)
End If
Next
Else
For i As Int32 = 0 To dsTmpMat.Tables(0).Rows.Count - 1
dsTmpMat.Tables(0).Rows(i)("BOM_IND") = 0
dsTmpMat.Tables(0).Rows(i)("BOM_DESC") = "BOM NOT CREATED"
Next
End If
End If