Auto Increment userdefined id - sql

Hi can anyone give me an idea how to create an auto generated id like ED01,ED02 etc., so that when i am entering data the id should be automatically incremented

Arguably this would be better done on the client side but you could
create a normal identity column
add a computed column doing the formatting.
Test script
DECLARE #ED TABLE (
ID INTEGER PRIMARY KEY IDENTITY(1, 1)
, UserID AS 'ED' + CAST(ID AS VARCHAR(32))
, I INTEGER
)
DECLARE #I INTEGER
SET #I = 0
WHILE #I < 100
BEGIN
SET #I = #I + 1
INSERT INTO #ED VALUES (#I)
END
SELECT * FROM #ED

Related

SQL server transfer column from one table to another

I am trying to transfer data from a column from one table to another, both columns are with unique identifiers and when i transfer the data it is copying the column after the end of the data of the second table. After the end of the other column of the second table (I am inserting first random integers in the first column and then I want to copy the information from another table in the same database and it is starting after the 135th row (I add 135 rows with random ints)). First table name : carBrand and column name model_id - second table name Cars11, model_idss - or whatever is the name...
THE QUESTION IS WHY is it inputting the iformation after the first input - example - i am inputting 135 random ints and after that i am trying to copy the information from the other table and when i am pasting it, the information is pasted after the 136th to the 270th sign
My query is looking like this for the new table
DECLARE #Min_Value AS int
SET #Min_Value= 15000
DECLARE #Max_Value AS int
SET #Max_Value = 1000000
DECLARE #n AS int
SET #n = 135
BEGIN TRANSACTION
DECLARE #uid uniqueidentifier
SET #uid = NEWID()
DECLARE #i AS int
SET #i = 1
WHILE #i <= #n BEGIN INSERT INTO Cars11([Model_prices]) VALUES(FLOOR(RAND(CHECKSUM(#uid))*(#Max_Value - #Min_Value +1) + #Min_Value)) SET #i += 1 SET #uid = NEWID() END COMMIT TRANSACTION
INSERT INTO Cars11(model_idss)
SELECT model_id
FROM carBrand
WHERE model_id <= 135;
It would be easier to parse your query if you used the code sample block (ctrl-k)
You need to do an update instead of insert for the second insert into Cars11.
Update changes already existing records, Insert creates new records.
Something like this:
DECLARE #Min_Value AS int
SET
#Min_Value = 15000
DECLARE #Max_Value AS int
SET
#Max_Value = 1000000
DECLARE #n AS int
SET
#n = 135
BEGIN TRANSACTION
DECLARE #uid uniqueidentifier
SET
#uid = NEWID()
DECLARE #i AS int
SET
#i = 1 WHILE #i <= #n
BEGIN
INSERT INTO
Cars11([Model_prices])
VALUES
(
FLOOR(
RAND(CHECKSUM(#uid)) *(#Max_Value - #Min_Value + 1) + #Min_Value
)
)
SET
#i + = 1
SET
#uid = NEWID()
END
COMMIT TRANSACTION
UPDATE Cars11
Set model_idss = (Select model_id FROM carBrand WHERE Cars11.model_idss = carBrand.model_id and carBrand.model_id <= 135));
Here are some other options for updating a column based on a query result

How to pass certain values from a table to a stored procedure

This is my problem. I have a table tbl_archivos with values like this:
Id desc namerc
---------------------------
1 arch1 RC201721091701
2 arch2 RC201724091701
I have to pass all the values of the column namerc in my table (above) to a stored procedure like parameter.
Like this :
sp_runproceess_billing 'RC201721091701'
and then the another value RC201724091701.
I am not allowed to use a cursor!
Please help me with this issue.
Thank you
try this solution
DECLARE #t AS TABLE(id INT PRIMARY KEY IDENTITY, namerc VARCHAR(50))
INSERT INTO #t
SELECT DISTINCT namerc FROM tbl_archivos
ORDER BY tbl_archivos
DECLARE #index INT = 1
DECLARE #max INT = (SELECT COUNT(*) FROM #t)
DECLARE #current_namerc VARCHAR(50)
WHILE #index <= #max
BEGIN
SELECT #current_namerc = namerc FROM #t WHERE id = #index
EXEC sp_runproceess_billing #current_namerc
SET #index = #index + 1
END

Violation of Primary Key Constraint Query

I was wondering if anyone could help me with my SQL code below. I am trying to insert all of the records from my BC_completions table into my Geodata table. If I exclude the ID column on the insert, I get a 'Msg 515... Cannot insert the value NULL into column 'ID'. But if I include it as below I get a 'Msg ...Violation of PRIMARY KEY constraint'.
What makes it more confusing is that if I manually typed in the value I get from #PK the database accepts it, so any help here would be great.
Thanks
DECLARE #PK AS INT
DECLARE #COUNT AS INT
DECLARE #RECORDCOUNT AS INT
SET #PK =
(SELECT TOP 1 ID FROM PRCORE.DBO.GEODATA
ORDER BY ID DESC)
SET #RECORDCOUNT =
(SELECT COUNT(*) FROM BC_COMPLETIONS)
SET #COUNT = 0
WHILE #COUNT < #RECORDCOUNT
BEGIN
SET #PK = #PK+1
SET #COUNT = #COUNT+1
INSERT INTO PRCORE.DBO.GEODATA
(ID,RecordType,ReferenceName,LocationDescription,Description,ORN,StartDate,ChgText)
SELECT #PK,189,REFVAL,ADDRESS,DSCRPN,ORN,RECPTD,AGTNAME
FROM BC_COMPLETIONS B
where #PK not in (select ID from prcore.dbo.geodata)
END
This is an issue with your loop and your WHERE constraint for the insert statement. You're selecting all of the records from BC_COMPLETIONS and assigning them to the same PK.
Instead, use the ROW_NUMBER() function to assign your PK which will allow you to do this all at once instead of one record at a time:
DECLARE #PK AS INT
DECLARE #RECORDCOUNT AS INT
SET #PK = (SELECT TOP 1 ID FROM PRCORE.DBO.GEODATA ORDER BY ID DESC) + 1
SET #RECORDCOUNT = (SELECT COUNT(*) FROM BC_COMPLETIONS)
INSERT INTO PRCORE.DBO.GEODATA (ID,RecordType,ReferenceName,LocationDescription,Description,ORN,StartDate,ChgText)
SELECT ROW_NUMBER() OVER(ORDER BY REFVAL) + #PK ,189,REFVAL,ADDRESS,DSCRPN,ORN,RECPTD,AGTNAME
FROM BC_COMPLETIONS B

How to insert split-ed amount into a table without using loop?

I need to split an amount into multiple part and insert into an table called installment, how can i implement it without using loop?
declare #installment as table (installment_index int identity(1,1),
amount money,
due_date datetime)
declare #total_amount money
declare #number_of_installment int
declare #amount money
declare #i int
declare #date datetime
set #date = getdate()
set #number_of_installment = 20
set #total_amount = 5001.00
set #amount = #total_amount / #number_of_installment
set #i= 1
while #i <= #number_of_installment
begin
insert into #installment
(amount,due_date) values (#amount, dateadd(month,#i,#date))
set #i = #i + 1
end
This would replace while loop:
;with numbers as (
select 1 number
union all
select number + 1
from numbers
where number < #number_of_installment
)
insert into #installment (amount,due_date)
select #amount, dateadd(month,number,#date)
from numbers
option (maxrecursion 0)
CTE numbers returns table of numbers from 1 to #number_of_installment
insert uses this table to insert #number_of_installment records to #installment.
EDIT:
I must mention that, according to this article, nothing beats auxiliary table of numbers/dates for similar purposes.

SQL transform semi-colon list into relationship table

I currently have a code table containing a list of types (Type_ID, Description), but they are saved in another table as ID;;ID;;ID...etc
I am looking for a script that will take those ID's and place them in a relationship table corresponding to there Type ID
For example in table A the Type_ID entries could look like:
1;;2;;4
1
3;;4
1;;2;;3;;4
I am completely stumped on how to accomplish this and any help is appreciated.
First of all, I would probably recommend going the UDF route (so that you don't reinvent the wheel). However, given that this sounds like a one-off activity, you could just use the following:
declare #output table (parentKey int, value int)
declare #values table (idx int identity(1, 1), parentKey int, value varchar(255))
-- Modify the below query to capture the data from your table
insert into #values (parentKey, value) values(1, '1;;2;;4'),(2, '1'),(3, '3;;4'),(4, '1;;2;;3;;4')
declare #i int
declare #cnt int
select #i = MIN(idx) - 1, #cnt = MAX(idx) from #values
while(#i < #cnt)
begin
select #i = #i + 1
declare #value varchar(255)
declare #key int
select #value = value, #key = parentKey from #values where idx = #i
declare #idx int
declare #next int
select #idx = 1
while(#idx <= LEN(#value))
begin
select #next = CHARINDEX(';;', #value, #idx)
if(#next > #idx)
begin
insert into #output (parentKey, value) values(#key, SUBSTRING(#value, #idx, #next - #idx))
select #idx = #next + 2
end
else
begin
insert into #output (parentKey, value) values(#key, SUBSTRING(#value, #idx, LEN(#value) - #idx + 1))
select #idx = LEN(#value) + 1
end
end
end
select * from #output
The #output table variable now contains the mapping you're looking for. You can either copy from that to your destination at the end, or you can remove #output from the query and substitute equivalent inserts directly into your relationship table.
Probably the easiest way is to use a UDF (User Defined Function), such as the Split functions outlined here.