Custom user autonumber - sql

I have been searching for a solution to this autonumber problem that I am having. There seems to be no definite answer anywhere.
I have a form which has a text field.
I want this form to display the next number from a field in a table.
Example: the table contains 3 records with the values D001, D002, D003
The form is used to enter new records (new data). So next time I enter data I want D004 to automatically show up on the text field for data code in the form.
How can this be done?

You can use the BeforeInsert event of the form:
Me!AutoNumber.Value = Format(Val(Nz(Right(DMax("[AutoNumber]", "[YourTable]"), 3), 0)) + 1, "\D000")

That is 1 way to do this is create a function to handle the autonumber problem u had
create function NextAutoNumber()
returns char(4)
as
begin
declare #lastval char(4)
set #lastval = (select max(autoNumber) from table)
if #lastval is null set #lastval = 'D001'
declare #i int set #i = right(#lastval,3) + 1 return 'C' + right('00' + convert(varchar(10),#i),3)
end
like this you can just call the function anytime and insert the auto number you need for the record

Related

weekly event select into file with different filenames depending on the variables(MariaDB)

I've always been a silent reader here until now.
Now I would like to ask for your expertise and post my ver first question here.
I have to achieve the following task on a weekly basis in my MariaDB via Events:
Every Week on Saturday night at midnight, i want to save the results of a certain view in an excel file (xlsx). The filename should be variable depending on the site_id and the current timestamp.
After saving the results into the file I want to cleanup the DB Tables with another Event, but the previous event must be successfully finished as a condition to start the cleanup event.
e.g.filename:
viewname_[site_id]_timestamp.xlsx
overall_weekly _3_01082022.xlsx
This is what I have so far:
EVENT 1(saving results into file):
CREATE EVENT overall_weekly
ON SCHEDULE EVERY 1 WEEK
STARTS TRUNCATE(CURRENT_TIMESTAMP) + '00:00:00' HOUR_SECONDS
ON COMPLETION PRESERVE
ENABLE
DO
DECLARE #path = char
DECLARE #view = char
DECLARE #site_id = int(3)
DECLARE #timestamp = timestamp
DECLARE #filetype = char(5)
DECLARE #full_filename = char
SET #path = "/home/reports/"
SET #view = "overall_traffic_weekly"
SET #site_id = 3
SET #timestamp = current_timestamp
SET #filetype = ".xlsx"
SET #full_filename = CONCAT(#path,#view,#site_id,#timestamp,#filetype)
SELECT * FROM
(
SELECT 'Column_name_1','Column_name2', ...
UNION ALL
(
SELECT * FROM overall_weekly
WHERE site_id = 3
)
) resulting_set
INTO OUTFILE #full_filename
FIELDS TERMINATED BY ';'
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '/n';
EVENT 2(cleanup):
EVENT 1 must be SUCCESSFULLY finished for event 2 to start.
IF event 1 finishes with errors, cleanup must not start.
CREATE EVENT cleanup
ON SCHEDULE EVERY 1 WEEK
STARTS TRUNCATE(CURRENT_TIMESTAMP) + '03:00:00' HOUR_SECONDS
ON COMPLETION PRESERVE
ENABLE
DO
TRUNCATE sourcetable1,
TRUNCATE Sourcetable2
;
Many thanks for reading.
Problem solved:
I used 2 tables instead and matched the 2 records together in a third table

SQL query (if column contains certain value move it to another column)

I'm relatively new to sql, so forgive me if my explanation isn't too clear. The column "invoice date week id" in the picture below shows in what week of a specific quarter a purchase was made. What I would like to do is this:
I would like to export all instances of W11,W12,and W13 into a new column called last3weeks. In other words, if the column contains week 11(W11), week 12(W12), and week 13(W13), then move it to a new created column called 'last3weeks'.
enter image description here
I recommend using Sql IF THEN ELSE statement.
here's an example for that,
CREATE FUNCTION IncomeLevel ( monthly_value INT )
RETURNS varchar(20)
BEGIN
DECLARE income_level varchar(20);
IF monthly_value <= 4000 THEN
SET income_level = 'Low Income';
ELSEIF monthly_value > 4000 AND monthly_value <= 7000 THEN
SET income_level = 'Avg Income';
ELSE
SET income_level = 'High Income';
END IF;
RETURN income_level;
END; //
you will just need to put on the condition you want ( W11 || W12 || W13 ) and set the value to a new column you can design by "as".

One-Time Use Randomized Number

Tables(columns) that are important here (there are more in my actual DB but I simplified):
Patients(PatientID, PatientNumber, DOB, Weight, RandomCode)
RandomNumbers(RandomNumberID, Available)
Sites(SiteID, SiteNumber)
Patients does not contain any data and is to be populated via a 3rd party GUI. RandomNumbers contains 50 entries. When a patient's data is first added to Patients, a random number 1-50 is selected, which is tied to RandomNumberID. The "available" column in RandomNumbers is treated as a boolean (T meaning available, F meaning unavailable). After the RandomNumberID is tied to a patient, that RandomNumberID cannot be used again (Available is switched to "F"). If an already used RandomNumber is assigned to a patient upon data entry, another randomly selected RandomNumberID is selected until one is found where Available is T.
Here is the storedproc that I've written so far:
GO
CREATE PROCEDURE uspPatientEntry
#intPatientID AS INTEGER OUTPUT
,#intPatientNumber AS INTEGER
,#intSiteID AS INTEGER
,#intRandomCode AS INTEGER
AS
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRANSACTION
SELECT #intPatientID = MAX (intPatientID) + 1
FROM TPatients TP (TABLOCKX)
SELECT #intPatientID = COALESCE(#intPatientID, 1)
SELECT #intPatientNumber = CONCAT(#intSiteID, #intPatientID)
INSERT INTO TPatients (intPatientID, intPatientNumber, intSiteID, intRandomCodeID)
VALUES (#intPatientID, #intPatientNumber, #intSiteID, #intRandomCode)
COMMIT TRANSACTION
GO
And here is another function I wrote to test it out:
DECLARE #intPatientID AS INTEGER = 0;
DECLARE #intSiteNumber AS INTEGER = 0;
DECLARE #intPatientNumber AS INTEGER = CONCAT(#intSiteNumber, #intPatientID);
DECLARE #intRandomCode AS INTEGER = FLOOR(RAND()*50)+1; -- This just picks a random integer 1-40. <- this is the heart of my question
EXECUTE uspPatientEntry #intPatientID OUTPUT, #intPatientNumber, 2, #intRandomCode
Would something like this work? Ignore syntax, just the general idea:
DECLARE #intRandomCode AS INTEGER;
SELECT #intRandomCode = FLOOR(RAND()*50+1;
FROM TRandomCodes TRC
WHERE TRC.blnAvailable = "T"
UPDATE TRandomCodes TRC
SET TRC.blnAvailable = "F"
WHERE #intRandomCode = TRC.intRandomNumberID;
Thank you

SQL, How to take into account previously populated records when populating a sequential number ID for a field in a nightly script

I am trying to include a clause in a script that runs nightly that will populate a three digit number into a field if that record meets a set of conditions. I will include the script that I have written for this below but I do not know how to account for the numbers that will have been populated on previous nights and keep the new numbers to be populated in sequential order. The numbers must start at 100 and go up by 1 each time a new record is found that meets the conditions.
All help is appreciated.
My current script:
DECLARE #myVar NVarchar(50)
SET #myVar = 99
UPDATE Database1..Thing
SET #myVar = Thing_Number_NEW = #myVar + 1
WHERE (Thing_Number = '' OR Thing_Number IS NULL)
AND Thing_Number_Needed = 'Yes'
AND Symbology IN (2, 3, 55, 66)
AND Thing_Number_New IS NULL
AND Last_edited_user is not null
Is this what you want?
UPDATE Database1..Thing
SET Thing_Number_NEW = COALESCE(n.max_Thing_Number_NEW + 1, 100)
FROM (SELECT MAX(Thing_Number_NEW) as max_Thing_Number_NEW FROM Database1..Thing) n
WHERE (Thing_Number = '' OR Thing_Number IS NULL)
Thing_Number_Needed = 'Yes' AND
Symbology IN (2, 3, 55, 66) AND
Thing_Number_New IS NULL AND
Last_edited_user is not null;

Can Multiple Parameter be used with LIKE in SQL

I am getting data from database in a format like "chem*,bio*" what i want to do is after i split the string into two i want to fetch all records containing "chem" and "bio" .. using LIKE with multiple parameter is something i want since CONTAIN will bring in irrelevant data too. Kindly help.
its something like this
assume:
#cwork2 ='chem*,bio*'
#cw1=#cw1 +'OR contains (name,'''+#Cwork1+''')'
#cw1=#cw1 +'OR name LIKE ('''+#Cwork1+''','%')'
Try this:
You can use pipeline (|) to achieve Or Condition
select * from Tablename where name like '[chem|bio]%';
just add them in an OR condition.
#cw1 = #cw1 OR name like '%chem%' OR name like '%bio%'
i found another way... although he answers provided are right on track but when talking about variables we cannot simply add on variables in the code. Hence forth i decided to put the variable in a #temp table, loop it through and then accordingly fetch data
insert into #publication select item from fsplit(#Work,',')
Declare #loopc int=1
while (#loopc <= (SELECT count(*) from #pub))
Begin
set #Cwork1= (select name from #pub where id= #loopc);
if CHARINDEX(#Cwork1,'*')<0
Begin
set #cw1='or pub.name ='''+#Cwork1+''')'
end
else
begin
set #Cwork1 = REPLACE(#Cwork1,'*','%');
set #cw1=#cw1 +'OR pub.name LIKE ('''+#Cwork1+''')'
end
set #loopc= #loopc +1;
end
set #cw1= (SELECT STUFF(#cw1, CHARINDEX('or', #cw1), LEN('or'), ''))
set #cw1= '('+#cw1+')'
set #Au2= #Au2 + ' and '+ #cw1