Sql server table copy from on database to another - sql-server

I want to copy data from dbase1.stockmaster to dbase2.stockmaster. Two of them having different columns.dbase1.stockmaster doesn't have a primary key. but I need to insert certain auto increment numbers to dbase2.stockmaster table p.k field. dbase2.stockmaster contains certain data which are referred on some other tables.
EDIT: (Adding below comment as a part of question)
declare #i int
set #i=0
while(#i <(select count(*) from NW000030.dbo.STOCKMST0001))
begin
set #i=#i+1
INSERT INTO NW000071.dbo.STOCKMST0001 (Stock_ID,ITEMCODE, ITEMNAME,RPROFIT1, RPROFIT2, RPROFIT3, QTY, LC, OLC, EANCODE, MRP, OPSTOCK, OPLC)
SELECT #i,itemcode, itemname, rprofit1, rprofit2, rprofit3, qty, lc, oLc FROM NW000030.dbo.STOCKMST0001
end

Try following format:
Use Database1
Insert into Schema1.Table1(columns)
select columns from Databse2.Schema2.Table2

Related

SQL Server trigger for multiple rows

I have a trigger:
ALTER TRIGGER [dbo].[tg_trs_uharian] ON [dbo].[master_st]
AFTER INSERT AS
BEGIN
SET NOCOUNT ON
declare #tgl_mulai varchar(10),
#tgl_selesai varchar(10),
#kdlokasi int,
#thn_harian int,
#date_diff int
declare #tugasID int;
declare #uangharian20 decimal(15,2);
declare #uangharian80 decimal(15,2);
declare #uangharian100 decimal(15,2);
select #tugasID=tugasID
from inserted
SET #thn_harian=CAST(YEAR(CONVERT(datetime, #tgl_mulai, 103)) AS INT);
SET #date_diff=((SELECT datediff(day,CONVERT([datetime],#tgl_mulai,(103)),CONVERT([datetime],#tgl_selesai,(103))))+1);
SET #uangharian100 = (
SELECT k.uh_nominal
FROM master_st m
LEFT OUTER JOIN ref_uharian AS k
ON k.uh_kdlokasi=m.kdlokasi AND k.uh_tahun=#thn_harian);
insert into trs_uangharian (tugasID, uangharian100) values
(#tugasID, #uangharian100);
END
How to make select #tugasID=tugasID from inserted applicable for multiple row inserted row table with different tugasID? It seems that my code is applicable for single row only.
It seems that #date_diff is not used
You use #thn_harian so we need #tgl_mulai, but it is NULL by default
So your INSERT statement has some problems.
I assumed that #tgl_mulai is a column of the original table master_st so I treat it as a column of "inserted" trigger internal table
ALTER TRIGGER [dbo].[tg_trs_uharian] ON [dbo].[master_st]
AFTER INSERT AS
BEGIN
SET NOCOUNT ON
insert into trs_uangharian(tugasID, uangharian100)
select
i.tugasID,
k.uh_nominal
from inserted i
left join ref_uharian AS k
ON k.uh_kdlokasi = i.kdlokasi AND
k.uh_tahun = CAST(YEAR(CONVERT(datetime, i.tgl_mulai, 103)) AS INT)
END
Please, this is a common problem among new SQL developers
SQL triggers work set-based.
Do not calculate any value using variables.
These can only store the last row's calculations in general.
Instead use Inserted and Deleted internal tables.
Your query is messed up a bit, so I can provide only general solution. Change INSERT part on something like this:
INSERT INTO trs_uangharian (tugasID, uangharian100)
SELECT i.tugasID,
k.uh_nominal
FROM inserted i
LEFT JOIN ref_uharian AS k
ON k.uh_kdlokasi=i.kdlokasi AND k.uh_tahun=#thn_harian
You should be able to replace the INSERT statement with this:
INSERT INTO trs_uangharian (tugasID, uangharian100)
SELECT
tugasID,
#uangharian100
FROM
inserted
However it looks like you also have an issue with #tgl_mulai and #tgl_selesai not being set to anything.

Most effective way to check sub-string exists in comma-separated string in SQL Server

I have a comma-separated list column available which has values like
Product1, Product2, Product3
I need to search whether the given product name exists in this column.
I used this SQL and it is working fine.
Select *
from ProductsList
where productname like '%Product1%'
This query is working very slowly. Is there a more efficient way I can search for a product name in the comma-separated list to improve the performance of the query?
Please note I have to search comma separated list before performing any other select statements.
user defined functions for comma separation of the string
Create FUNCTION [dbo].[BreakStringIntoRows] (#CommadelimitedString varchar(max))
RETURNS #Result TABLE (Column1 VARCHAR(max))
AS
BEGIN
DECLARE #IntLocation INT
WHILE (CHARINDEX(',', #CommadelimitedString, 0) > 0)
BEGIN
SET #IntLocation = CHARINDEX(',', #CommadelimitedString, 0)
INSERT INTO #Result (Column1)
--LTRIM and RTRIM to ensure blank spaces are removed
SELECT RTRIM(LTRIM(SUBSTRING(#CommadelimitedString, 0, #IntLocation)))
SET #CommadelimitedString = STUFF(#CommadelimitedString, 1, #IntLocation, '')
END
INSERT INTO #Result (Column1)
SELECT RTRIM(LTRIM(#CommadelimitedString))--LTRIM and RTRIM to ensure blank spaces are removed
RETURN
END
Declare #productname Nvarchar(max)
set #productname='Product1,Product2,Product3'
select * from product where [productname] in(select * from [dbo].[![enter image description here][1]][1][BreakStringIntoRows](#productname))
Felix is right and the 'right answer' is to normalize your table. Although, maybe you have 500k lines of code that expect this column to exist as it is. So your next best (non-destructive) answer is:
Create a table to hold normalize data:
CREATE TABLE ProductsList2 (ProductId INT, ProductName VARCHAR)
Create a TRIGGER that on UPDATE/INSERT/DELETE maintains ProductList2 by splitting the string 'Product1,Product2,Product3' into three records.
Index your new table.
Query against your new table:
SELECT *
FROM ProductsList
WHERE ProductId IN (SELECT x.ProductId
FROM ProductsList2 x
WHERE x.ProductName = 'Product1')

SQL Server: how to re-use SCOPE_IDENTITY()?

I want to do some sort of "copy-paste" of one row in the table creneau. This row has a one-to-many relationship with table creneau_jour. Thus I'd like to duplicate all the rows of this relationship too. I'm trying to do what I've done with MySQL but I'm missing something but dont know why:
INSERT INTO [RdV].[dbo].[creneau]
([libelle]
,[debut]
,[fin]
,[heure_debut]
,[duree])
SELECT
'Encore !!!', debut, fin, heure_debut, duree
FROM
creneau
WHERE
id = 1;
INSERT INTO [RdV].[dbo].[creneau_jour]
([creneau_id] ,[jour_semaine])
VALUES (
SELECT SCOPE_IDENTITY(), SELECT jour_semaine FROM creneau_jour WHERE id=1
);
Any idea of what I'm doing wrong?
DECLARE #SCOPEIDENTITY INT;
INSERT INTO [RdV].[dbo].[creneau]
([libelle]
,[debut]
,[fin]
,[heure_debut]
,[duree])
SELECT 'Encore v3',debut,fin,heure_debut,duree FROM creneau WHERE id=1;
SET #SCOPEIDENTITY = SCOPE_IDENTITY();
INSERT INTO [RdV].[dbo].[creneau_jour] ([creneau_id] ,[jour_semaine])
SELECT #SCOPEIDENTITY, jour_semaine FROM creneau_jour WHERE creneau_id=1
;
GO
You can forget about using SCOPE_IDENTITY() and use OUTPUT as part of the INSERT, so that you can set a variable with a value from the newly created row.
One such advantage to this method is that if you ever turn on identity insert then #SCOPE_IDENTITY wouldn't work, but the method using OUTPUT would.
DECLARE #Identity INT
INSERT INTO [RdV].[dbo].[creneau]
([libelle]
,[debut]
,[fin]
,[heure_debut]
,[duree])
OUTPUT inserted.IdentityColumn INTO #Identity
SELECT
'Encore !!!', debut, fin, heure_debut, duree
FROM
creneau
WHERE
id = 1
INSERT INTO [RdV].[dbo].[creneau_jour]
([creneau_id] ,[jour_semaine])
VALUES (
SELECT #Identity, SELECT jour_semaine FROM creneau_jour WHERE id=1
);
Try this one
DECLARE #SCOPEIDENTITY INT;
INSERT INTO [RdV].[dbo].[creneau]
([libelle]
,[debut]
,[fin]
,[heure_debut]
,[duree])
SELECT 'Encore v3',debut,fin,heure_debut,duree FROM creneau WHERE id=1;
SET #SCOPEIDENTITY = SCOPE_IDENTITY();
INSERT INTO [RdV].[dbo].[creneau_jour] ([creneau_id] ,[jour_semaine])
SELECT #SCOPEIDENTITY, jour_semaine FROM creneau_jour WHERE creneau_id=1;
GO

sql server merge with multiple insert when not matched

I'm using MERGE in my query and i'm making INSERT on clause WHEN NOT MATCHED THEN, but then i would like to get the inserted row identity and make another INSERT to some other table. Query for now is:
ALTER PROCEDURE [dbo].[BulkMergeOffers]
#data ImportDataType READONLY
AS
SET NOCOUNT ON;
DECLARE #cid int = 0
MERGE dbo.oferta AS target
USING #data AS source
ON (target.nr_oferty = source.nr_oferty)
WHEN NOT MATCHED THEN
INSERT (nr_oferty,rynek,typ_transakcji, typ_nieruchomosci,cena,powierzchnia, rok_budowy, wojewodztwo, miasto, dzielnica, ulica, opis, wspolrzedne, film, zrodlo, KontaktStore, data, forma_wlasnosci, stan_techniczny, liczba_pokoi, liczba_peter, pietro, material, kuchnia, pow_dzialki, typ_dzialki, woda,gaz, prad,sila, przeznaczenie,lokal_dane)
VALUES (source.nr_oferty,source.rynek,source.typ_transakcji, source.typ_nieruchomosci,source.cena,source.powierzchnia, source.rok_budowy, source.wojewodztwo, miasto, source.dzielnica, source.ulica, source.opis, source.wspolrzedne, source.film, source.zrodlo, source.KontaktStore, source.data, source.forma_wlasnosci, source.stan_techniczny, source.liczba_pokoi, source.liczba_peter, source.pietro, source.material, source.kuchnia, source.pow_dzialki, source.typ_dzialki, source.woda,source.gaz, source.prad,source.sila, source.przeznaczenie,source.lokal_dane);
So as you see i need to insert some values to the target table based on source data, then i need to take the insert identity and insert it into another table but also based on some source data, so something like that, just after the first insert:
SET #cid = SCOPE_IDENTITY();
if source.photo is not null
begin
insert into dbo.photos(offerID, file) values (#cid, source.photo);
end
But i can't assemble it, a have no access to the source no more, also if statement show error :
"the multi-part identifier
source.photo can not be bound"
but it is there. Just for clarity ImportDataType is a table-valued parameter.
Please HELP
If you don't need the WHEN MATCHED part of the MERGE statement in your query, there's no real reason to use MERGE. You could use INSERT with an outer join or NOT EXISTS statement.
In either case, you can use the OUTPUT clause to retrieve the inserted identity value an pass it on to a second query.
I've extended your example:
<stored procedure header - unchanged>
--declare a table variable to hold the inserted values data
DECLARE #newData TABLE
(nr_oferty int
,newid int
) -- I'm guessing the datatype for both columns
MERGE dbo.oferta AS target
USING #data AS source
ON (target.nr_oferty = source.nr_oferty)
WHEN NOT MATCHED THEN
INSERT (nr_oferty,rynek,typ_transakcji, typ_nieruchomosci,cena,powierzchnia, rok_budowy, wojewodztwo, miasto, dzielnica, ulica, opis, wspolrzedne, film, zrodlo, KontaktStore, data, forma_wlasnosci, stan_techniczny, liczba_pokoi, liczba_peter, pietro, material, kuchnia, pow_dzialki, typ_dzialki, woda,gaz, prad,sila, przeznaczenie,lokal_dane)
VALUES (source.nr_oferty,source.rynek,source.typ_transakcji, source.typ_nieruchomosci,source.cena,source.powierzchnia, source.rok_budowy, source.wojewodztwo, miasto, source.dzielnica, source.ulica, source.opis, source.wspolrzedne, source.film, source.zrodlo, source.KontaktStore, source.data, source.forma_wlasnosci, source.stan_techniczny, source.liczba_pokoi, source.liczba_peter, source.pietro, source.material, source.kuchnia, source.pow_dzialki, source.typ_dzialki, source.woda,source.gaz, source.prad,source.sila, source.przeznaczenie,source.lokal_dane)
OUTPUT inserted.nr_oferty, inserted.<tableId> INTO #newData;
-- replace <tableId> with the name of the identity column in dbo.oftera
insert into dbo.photos(offerID, file)
SELECT nd.newid, pt.photo
FROM #data AS pt
JOIN #newData AS nd
ON nd.nr_oferty = pt.nr_oferty
WHERE pt.photo IS NOT NULL

SQL server Query help

I am passing a list of zipcodes to a stored proc (say 11111, 11112, 11113, 11114, 11115) and the zip code table contains only few rows (say 11111, 11112, 11113) and now I want to write a query which returns the zip codes that are not exists in the table (11114 and 11115)
Could anyone please help me to write a query like this?
Thanks in advance.
Not knowing your exact implementation, this quick and dirty query should be adaptable to what you're trying. Select the zip codes from the list you passed which aren't in the full table of zip codes:
SELECT ZipCode
FROM PassedList
WHERE ZipCode NOT IN (
SELECT DISTINCT ZipCode
FROM ZipCodeTable
)
This article uses CTE to take your string of entries, convert to a table so you can include in a query: http://www.sqlservercentral.com/articles/CTE/67974/
You have use a JOIN to build your first query.
Now you'll need a RIGHT JOIN/WHERE to include all items in your zip list which correspondent record on zip table is null
EDIT: Here is a sample
CREATE TABLE ZipCodesTable(Code int NOT NULL)
CREATE TABLE ZipCodesList (Code int NOT NULL)
INSERT INTO ZipCodesTable (Code) VALUES (11111)
INSERT INTO ZipCodesTable (Code) VALUES (11112)
INSERT INTO ZipCodesTable (Code) VALUES (11113)
INSERT INTO ZipCodesList (Code) VALUES (11111)
INSERT INTO ZipCodesList (Code) VALUES (11112)
INSERT INTO ZipCodesList (Code) VALUES (11113)
INSERT INTO ZipCodesList (Code) VALUES (11114)
INSERT INTO ZipCodesList (Code) VALUES (11115)
SELECT ZipCodesList.Code
FROM ZipCodesTable RIGHT
JOIN ZipCodesList
ON ZipCodesTable.Code = ZipCodesList.Code
WHERE ZipCodesTable.Code IS NULL
No need to create a table in SQL use a temp table in the stored proc. If you need to pass in the zips as string use this. If you have a table valued parameter you can pass them in as a table.
CREATE PROCEDURE spCheckZip
#Zips varchar(256) --space delimited list of zips
AS
IF OBJECT_ID('tempdb..#ZipCheck') IS NOT NULL
DROP TABLE #ZipCheck
CREATE TABLE #ZipCheck (zipcode string) --Note string not int for zips with leading 0's.
IF CharIndex(' ',#Zips) > 1
BEGIN
Declare #StartPos as int
Declare #ZipCd As Varchar(16)
set #StartPos = 2
set #ZipCd = substring(#Zips,1,CharIndex(',',#Zips))
WHILE #StartPos > 1 and #StartPos < Len(#Zips)
BEGIN
INSERT Into #ZipCheck (zipcode)
SELECT Substring(#ZipCd,1,len(#ZipCd)-1)
SET #StartPos = charindex(',',#Zips, #StartPos)+1
SET #ZipCd = substring(#Zips,#StartPos,CharIndex(',',#Zips))
END
END
SELECT ZipCode
FROM ZipCheck LEFT JOIN YourZipTable on ZipCheck.zipcode=YourZipTable.YourZipField
WHERE YourZipTable.YourZipField IS NULL

Resources