Copying values from TABLEA to TABLEB with use of Cursor - sql

I'd like to copy values from TableA to TableB using cursor but getting troubles all the time. Here is my code:
DROP TABLE #Firmy
DROP TABLE #Faktury
CREATE TABLE #Firmy (
idfirmy VARCHAR(255)
)
INSERT INTO #Firmy VALUES ('00001936')
INSERT INTO #Firmy VALUES ('00002059')
CREATE TABLE #Faktury (
idfirmy VARCHAR(255)--,
--idfaktury VARCHAR(255)
)
DECLARE fakturyc CURSOR FOR SELECT * FROM #Firmy
FOR loop1 AS fakturyc
DO
INSERT INTO #Faktury VALUES fakturyc
END FOR
Getting "Syntax error near loop1". Can someone help me with solving this? Thanks :)

This is actually T-sql: but may work in sybase as well
DROP TABLE #Firmy
DROP TABLE #Faktury
CREATE TABLE #Firmy (
idfirmy VARCHAR(255)
)
INSERT INTO #Firmy VALUES ('00001936')
INSERT INTO #Firmy VALUES ('00002059')
CREATE TABLE #Faktury (
idfirmy VARCHAR(255)--,
--idfaktury VARCHAR(255)
)
declare #col1 varchar(10)
declare copy cursor for
select idfirmy from #Firmy -- select top 1 * from #Firmy
open copy
fetch next from copy into #col1
while ##FETCH_STATUS=0
begin
insert into #Faktury(idfirmy) values(#col1)
fetch next from copy into #col1
end
close copy
deallocate copy
select * from #Faktury
select * from #Firmy
The simplified Query will be
insert into #Faktury
select * from #Firmy

Related

Inserting into a Table the result between a variable and a table parameter

Having the following procedure:
CREATE PROCEDURE [dbo].[Gest_Doc_SampleProc]
#Nome nvarchar(255),
#Descritivo nvarchar(255),
#SampleTable AS dbo.IDList READONLY
AS
DECLARE #foo int;
SELECT #foo=a.bar FROM TableA a WHERE a.Nome=#Nome
IF NOT EXISTS (SELECT a.bar FROM TableA a WHERE a.Nome=#Nome)
BEGIN
INSERT INTO TableA VALUES (#Nome,#Descritivo)
INSERT INTO TableB VALUES (scope_identity(),#SampleTable)
END
I am trying, as shown, inserting into TableB all the values of SampleTable, together with the scope_identity.
SampleTable is as:
CREATE TYPE dbo.SampleTable
AS TABLE
(
ID INT
);
GO
How can I correctly achieve this?
The right way to do this type of work is the OUTPUT clause. Although technically not needed for a single row insert, you might as well learn how to do it correctly. And even what looks like a single row insert can have an insert trigger that does unexpected things.
PROCEDURE [dbo].[Gest_Doc_SampleProc] (
#Nome nvarchar(255),
#Descritivo nvarchar(255),
#SampleTable AS dbo.IDList
) READONLY AS
BEGIN
DECLARE #ids TABLE (id int);
DECLARE #foo int;
SELECT #foo = a.bar
FROM TableA a
WHERE a.Nome = #Nome;
IF NOT EXISTS (SELECT 1 FROM TableA a WHERE a.Nome = #Nome)
BEGIN
INSERT INTO TableA (Nome, Descritive)
OUTPUT Inserted.id -- or whatever the id is called
INTO #ids;
VALUES (#Nome,#Descritivo)
INSERT INTO TableB (id, sampletable)
SELECT id, #SampleTable
FROM #ids;
END;
END; -- Gest_Doc_SampleProc
In addition to using OUTPUT, this code also adds column lists to the INSERTs. That is another best practice.

Get Scope identity for multiple inserts

For table1 Inserted 3 records
It should get those three identities and it should insert 3 records in table3 (but it’s not happening- it inserts 3 records with same identity ie.last scope identity)
create table table1(ID INT identity(1,1),Name varchar(50))
insert into table1 values('Ram'),('Sitha'),('Laxman')
create table table1(ID INT identity(1,1),Name varchar(50))
create table table3(ID INT ,Name varchar(50))
insert into table2(Name)
select Name from table1
declare #id int;
set #id= (select scope_Identity())
begin
insert into table3(ID,Name)
select #id,Name from table2
end
select * from table2
select * from table3
How can get all identities to insert do I need to write a loop (or) do I need to Create a trigger.
Please give me a solution I am strugguling from past 4 hours.
Thanks in anvance
Use the OUTPUT clause to handle multi-row inserts:
INSERT INTO dbo.table2(Name)
OUTPUT inserted.ID, inserted.Name INTO table3
SELECT Name FROM dbo.table1;
You can use the OUTPUT clause to get the identity from any number of inserts.
create table table1(ID INT identity(1,1),Name varchar(50))
DECLARE #T1 Table (ID int, name varchar(50))
insert into table1
OUTPUT inserted.ID, Inserted.Name INTO #T1
values('Ram'),('Sitha'),('Laxman')
DECLARE #IdentityId INT,#Count INT=1
DECLARE #temp AS TABLE (Id INT IDENTITY ,Name NVARCHAR(100))
INSERT INTO #temp(Name)
SELECT Name FROM table1
WHILE #Count <=(SELECT COUNT(SId) FROM #temp)
BEGIN
INSERT INTO table2(Name)
SELECT Name FROM #temp
WHERE Id=#Count
SET #IdentityId = SCOPE_IDENTITY()
INSERT INTO tabel3(#IdentityId,Name)
SELECT 3, #IdentityId,1,GETDATE()
SET #Count=#Count+1
END

INSERT ONLY SPECIFIC COLUMN FROM A STORED PROCEDURE RESULT

I want to know if it is possible to insert to a table from a specific column of result from a stored procedure?
Something like:
declare #temp as table(
id int
)
insert #temp
exec getlistofStudents --returns multiple columns
this is an example only, Thanks for the help..
You can take a 2 step approach. First INSERT INTO a #TempTable, then populate the #TempVariable with another INSERT INTO, selecting the single column.
DECLARE #temp AS TABLE
(
ID int
);
CREATE TABLE #tempTable1
(
Column1 int,
Column2 int
);
INSERT INTO #tempTable1
Exec getlistofStudents
INSERT INTO #temp
SELECT Column1 FROM #tempTable1

Passing multiple parameters into a Table valued function

I have a table valued function as below. When I am trying to pass more than one parameter at the same time I am getting a error like "Function has too many arguments specified" .
CREATE FUNCTION [dbo].[GetCompanyUsers](#CompanyId BIGINT)
RETURNS #Users TABLE (Id BIGINT,Contact NVarchar(4000))
AS
BEGIN
INSERT INTO #Users(Id,Contact)
SELECT [Id]
,ISNULL([FirstName],'')+' ' +ISNULL([LastName],'') AS [Contact]
FROM [dbo].[CompanyAddressesContacts]
WHERE [CompanyId]=#CompanyId
ORDER BY ISNULL([FirstName],'')+' ' +ISNULL([LastName],'')
RETURN
END
What modifications I require in the above code so that it allows multiple values and I need to use the function in a "WHERE" condition in my dataset.
WHERE(Document_RFIs.CreatedBy IN
(SELECT Id FROM dbo.GetCompanyUsers(#CompanyId)))
This may help (but the fundamental problem is - passing a comma delimited string is something to be avoided unless absolutely necessary - which explains why you have received so few answers):-
--set nocount on
--create table #Document_RFIs (
-- CreatedBy varchar(50),
-- columna varchar(50),
-- columnb varchar(50),
-- columnc varchar(50)
--)
--insert into #Document_RFIs values
-- ('albert einstein','another','value',null),
-- ('marie curie','some',null,'tuna'),
-- ('isaac newton','why','not','provide'),
-- ('kepler','some','test','data'),
-- ('robert boyle','with','your','question'),
-- ('john dalton','it',null,'would'),
-- ('enrico fermi','make','helping','you'),
-- ('peter higgs','so','much','easier')
--create table #CompanyAddressesContacts (
-- companyid int,
-- firstname varchar(50),
-- lastname varchar(50)
--)
--insert into #CompanyAddressesContacts values (22,'albert','einstein')
--insert into #CompanyAddressesContacts values (23,'marie','curie')
--insert into #CompanyAddressesContacts values (23,'isaac','newton')
--insert into #CompanyAddressesContacts values (24,null,'kepler')
--insert into #CompanyAddressesContacts values (25,'robert','boyle')
--insert into #CompanyAddressesContacts values (25,'enrico','fermi')
--insert into #CompanyAddressesContacts values (26,'peter','higgs')
declare #ids varchar(1024)
set #ids='23,24,25'
create table #id (
companyid int
)
declare #pos int
while DATALENGTH(#ids)>0 begin
set #pos=charindex(',',#ids)
if #pos>0 begin
insert into #id values (left(#ids,#pos-1))
set #ids=SUBSTRING(#ids,#pos+1,DATALENGTH(#ids))
end else begin
insert into #id values (#ids)
set #ids=''
end
end
select d.*
from #Document_RFIs d
where exists(
select cac.*
from #CompanyAddressesContacts cac
join #id i on i.companyid=cac.companyid
where isnull(cac.firstname+' ','')+isnull(cac.lastname,'')=d.CreatedBy
)
--drop table #id
--drop table #Document_RFIs
--drop table #CompanyAddressesContacts
I would do something like this:
First convert your #CompanyId to rows
WITH CompanyIds AS (
SELECT Id
FROM CompanyTable -- Same as the source of the #CompanyId
WHERE Id IN (#CompanyId)
)
Then extract all users
,Users AS (
SELECT UserId
FROM CompanyIds
CROSS APPLY (
SELECT Id AS UserId
FROM dbo.GetCompanyUsers(CompanyIds.Id)
) AS CA1
)
And then use it in the where statement
WHERE Document_RFIs.CreatedBy IN (SELECT UserId
FROM Users)

How to delete duplicate rows from table from DbVisualiser

I have a table called ORG_MAP, it contained 200 records, I executed a query to copy those 200 records to other table called ORG_MAP_1 (duplicate table of ORG_MAP), but what happened was the same 200 records got inserted into the same ORG_MAP table.
Now I want to remove those duplicated records. I don't know how to do that.
Please help me. I'm using db visualizer8.0.11 version.
the query I used was:
INSERT INTO METRICS.ORG_MAP (REPORT_END_DATE,ENTITY,ENTITY_TYPE,RELATIONSHIP,TARGET,TARGET_TYPE)
SELECT REPORT_END_DATE,ENTITY,ENTITY_TYPE,RELATIONSHIP,TARGET,TARGET_TYPE
FROM METRICS.ORG_MAP
i dont think there is any direct solution for your problem
but i have done some work around may be useful for you....
create table #table(id int,c varchar(2))
insert into #table values('1','a')
insert into #table values('1','a')
insert into #table values('2','b')
insert into #table values('2','b')
insert into #table values('3','c')
insert into #table values('3','c')
insert into #table values('4','d')
insert into #table values('5','d')
declare #table table(uid int,id int ,c varchar(2));
with tbl as (
select ROW_NUMBER() OVER(ORDER BY id DESC) AS uid ,id,c from #table
)
insert into #table select * from tbl
declare #tmpid int,#tmpuid int,#cnt int
declare tmpc cursor
for select uid,id from #table;
open tmpc
fetch next from tmpc
into #tmpuid,#tmpid
while ##FETCH_STATUS = 0
BEGIN
set #cnt = (select COUNT(id) from #table where id = #tmpid)
IF (#cnt > 1)
BEGIN
delete from #table where uid = #tmpuid
END
fetch next from tmpc
into #tmpuid,#tmpid
END
CLOSE tmpc;
DEALLOCATE tmpc;
select * from #table
drop table #table