SQL server transfer column from one table to another - sql

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

Related

Updating Null records of a table by invoking stored procedure throws error 'Subquery returned more than one value'

I am trying to update all null values of a column with Uuid (generated with the help of a stored procedure GetOptimizedUuid). While doing so I am getting an error
Subquery returned more than 1 value
I could understand the causes of error but none of my fix helped out.
I tried out with some loops but it doesn't fix
BEGIN
DECLARE #no INT;
DECLARE #i INT;
SET #no = (SELECT COUNT(id) FROM table1)
SET #i = 0;
WHILE #i < #no
BEGIN
DECLARE #TempUuid TABLE(SeqUuid UNIQUEIDENTIFIER, OptimizedUuid UNIQUEIDENTIFIER)
INSERT INTO #TempUuid
EXECUTE [Sample].[dbo].[GetOptimizedUuid]
UPDATE table1
SET col2 = (SELECT OptimizedUuid FROM #TempUuid)
WHERE col2 IS NULL;
SET #i = #i + 1;
END
END
Help me to sort out this, Thanks!
Not entirely sure what you're doing - what do you need to call this GetOptimizedUuid stored procedure? Can't you just use NEWID() to get a new GUID?
Anyway - assuming you have to call this stored procedure, I assume you'd call it once before the loop, to get the ID's you need - and then you get the top (1) UUID from the table and update one row in your database table - and then you also need to remove that UUID that you've just used from the temp table, otherwise you keep re-using the same ID over and over again....
Try something like this:
BEGIN
DECLARE #no INT;
DECLARE #i INT;
SET #no = (SELECT COUNT(id) FROM table1)
SET #i = 0;
-- define and fill the table *ONCE* and *BEFORE* the loop
DECLARE #TempUuid TABLE(SeqUuid UNIQUEIDENTIFIER, OptimizedUuid UNIQUEIDENTIFIER)
INSERT INTO #TempUuid
EXECUTE [Sample].[dbo].[GetOptimizedUuid]
-- declare a UUID to use
DECLARE #NewUuid UNIQUEIDENTIFIER;
WHILE #i < #no
BEGIN
-- get the first UUID from the temp table
SELECT TOP (1) #NewUuid = OptimizedUuid
FROM #TempUuid;
-- update your table
UPDATE table1
SET col2 = #NewUuid
WHERE col2 IS NULL;
-- *REMOVE* that UUID that you've used from the table
DELETE FROM #TempUuid
WHERE OptimizedUuid = #NewUuid;
SET #i = #i + 1;
END
END

The best method to update every row in SQL Server

I have code like this to create random table: (http://dba.fyicenter.com/faq/sql_server/Creating_a_Large_Table_with_Random_Data_for_Indexes.html)
-- Create a table with primary key
CREATE TABLE fyi_random
(
id INT,
rand_integer INT,
rand_number numeric(18,9),
rand_datetime DATETIME,
rand_string VARCHAR(80)
);
-- Insert rows with random values
DECLARE #row INT;
DECLARE #string VARCHAR(80), #length INT, #code INT;
SET #row = 0;
WHILE #row < 100000
BEGIN
SET #row = #row + 1;
-- Build the random string
SET #length = ROUND(80*RAND(),0);
SET #string = '';
WHILE #length > 0
BEGIN
SET #length = #length - 1;
SET #code = ROUND(32*RAND(),0) - 6;
IF #code BETWEEN 1 AND 26
SET #string = #string + CHAR(ASCII('a')+#code-1);
ELSE
SET #string = #string + ' ';
END
-- Ready for the record
SET NOCOUNT ON;
INSERT INTO fyi_random
VALUES (#row,
ROUND(2000000*RAND()-1000000,0),
ROUND(2000000*RAND()-1000000,9),
CONVERT(DATETIME, ROUND(60000*RAND() - 30000, 9) ),
#string)
END
PRINT 'Rows inserted: '+CONVERT(VARCHAR(20),#row);
GO
I want to update every row (for example update column rand_string with some new random string). What is the best method? When I'm trying to do this by while loop performance decreases with increasing rows:
...
SET NOCOUNT ON;
UPDATE random_data
SET rand_string = #string
WHERE id = #row;
I also tried to use cursor statement and it's better but why while loop is so slow? And is there another way to do this better?
If you want to update every row in a table then just omit the where clause in the update statement.

Update table in chunks

I am trying to update a large table in chunks and transactions.
This query runs endlessly in case column1 is not updated for some reason. I have another nested query there, which does not necessarily return a value, so some column1's remain as null after the update. This puts my query into an endless loop.
How can I specify a position for "update top" to start with?
Thanks in advance.
declare #counter int
declare #total int
declare #batch int
set #total = (SELECT COUNT(*) FROM table with(nolock))
set #counter = 0
set #batch = 1000
while (#counter < (#total/#batch) + 1)
begin
BEGIN TRANSACTION
set #counter = #counter + 1
Update TOP ( #batch ) table
SET column1 = 'something'
where column1 is null
Commit transaction
end

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.

Auto Increment userdefined id

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