SQL Server MERGE statement reporting invalid column - sql

I have this MERGE statement that works fine on one database server and I need to deploy it to another database server for a different country's office. I used RedGate's SQL Compare and both databases have what is required.
MERGE dbo.MfgGrouping AS Target
USING
(SELECT JC.job_number
, JC.Quote_NO
, PMG.MfgGroupingID
, SR.Description
, MG.GroupingNumber
, MG.GroupingDesc
, MG.Assigned
, MG.AssignedDate
, MG.AssignedBy
, MG.[Priority]
, P.Record_no
FROM dbo.Product AS P
INNER JOIN dbo.ProductMfgGrouping AS PMG ON P.Record_no = PMG.Record_no
INNER JOIN dbo.Job_Control AS JC ON P.Quote_NO = JC.Quote_NO
LEFT OUTER JOIN dbo.MfgGrouping AS MG ON PMG.MfgGroupingID = MG.MfgGroupingID
LEFT OUTER JOIN dbo.ShopRouting AS SR ON MG.ShopRoutingID = SR.ShopRoutingID
WHERE (JC.job_number = #SalesOrder)) AS Source
ON(Target.MfgGroupingID = Source.MfgGroupingID)
WHEN MATCHED
THEN
UPDATE
SET Target.GroupingNumber = Source.GroupingNumber,
Target.Assigned = Source.Assigned,
Target.AssignedDate = Source.AssignedDate,
Target.AssignedBy = Source.AssignedBy
WHEN NOT MATCHED BY TARGET
THEN
INSERT(GroupingNumber, Assigned, AssignedDate, AssignedBy, Record_no)
VALUES(1, Source.Assigned, Source.AssignedDate, Source.AssignedBy, Source.Record_no);
The problem that I'm experiencing is that I get an error:
invalid column name 'Record_no'
on the deployed database; but not on the original DB. Everything looks the same and good to me.
Can someone please shed some light on this?
The only difference is the original database is SQL Server 2014 and the deployed database is SQL Server 2008.
Thanks,
Jimmy

Related

Msg 7202, Level 11, State 2, Line 1 Could not find server 'acct' in sys.servers

Would you know what could be the code error on query with my tables and server database connection, I normally list my query in the following format and today it provides me with the same continued error and only this query is displaying this type of error. My tables are referencing the correct database due to the reason that this is the only database that hods these tables. My query code listed below, maybe its missing something.
SELECT Distinct
'CA' AS 'Server'
, DATENAME(month, res.Move_in_Date) [MonthName]
, DATEPART(day, res.Move_in_Date) [Day]
, DATENAME(WEEKDAY, res.Move_in_Date) [Weekday]
, res.Move_in_Date
, res.Move_out_Date
, ge.Entity_Number
, bld.Building_Name
, addr.Address2
, addr.City
, addr.State
, addr.Zip_Code
, bld.Building_ID
, unts.Unit_Number
, res.First_Name
, res.Last_Name
, ge.Active AS GL_Entities_Active
, bld.Building_Active
FROM
acct.cam_ca.dbo.residents AS res
INNER JOIN
acct.cam_ca.dbo.units AS unts
ON res.Unit_ID = unts.Unit_ID
INNER JOIN
acct.cam_ca.dbo.addresses AS addr
INNER JOIN
acct.cam_ca.dbo.gl_entities AS ge
ON addr.Address_ID = ge.Address_ID
INNER JOIN
acct.cam_ca.dbo.buildings AS bld
ON ge.GL_Entity_ID = bld.GL_Entity_ID ON unts.Building_ID = bld.Building_ID
WHERE
ge.Active = 1
AND ge.Entity_Number = 1
AND bld.Building_Active = 1
AND res.Move_in_Date BETWEEN '20200101 00:00:00.000 AM' AND '20200707 11:59:59 PM'
ORDER BY
ent.Entity_Number
, res.Move_in_Date
As can be read from the error message the server mentioned in the query is not available in metadata view sys.servers.There are two possibilities,
The server "acct" is not available.
The server "acct" is defined but could have a different name
defined.
Troubleshoot by running queries Run the query below to list all available servers ,
select name,data_source from sys.servers
Try to identify the name corresponding to the data_source and use that name instead of acct for the server in your query.
If you are unable to identify a relevant entry, contact DBA to provide the details of the server.
Your query is trying to access tables on a different server, accessed through a linked server called acct. For example, in your code you have acct.cam_ca.dbo.residents. Here:
residents is the table name
dbo is the schema name
cam_ca is the database name
acct is the linked server name
Either the linked server used to exist but has been deleted by a DBA, or you are running your query on a different server from the one where it works and this new server does not have the acct linked server set up, or you have changed the query.

Update a table with results from multiple tables

Currently using Microsoft SQL Server 2012 (Management Studio), looking to update a column in a table with a query which uses data from another table.
This is the query I am running:
SELECT
tblGeneralVehicleInformation.EngineerVehicleReg, tblModel.Model_ID,
tblModel.VanOrCar, tblModel.Model, tblMake.Make_ID,
tblMake.WarrantyCars, tblMake.WarrantyVans,
tblMake.WarrantyCarMonths, tblMake.WarrantyVanMonths,
tblGeneralVehicleInformation.PurchaseDate,
tblGeneralVehicleInformation.Mileage
FROM
tblGeneralVehicleInformation
INNER JOIN
tblModel ON tblGeneralVehicleInformation.Model_IDFK = tblModel.Model_ID
INNER JOIN
tblMake ON tblGeneralVehicleInformation.Make_IDFK = tblMake.Make_ID
UPDATE dbo.tblGeneralVehicleInformation
SET WarrantyId = '1'
WHERE (tblModel.VanOrCar = N'Van')
AND (Mileage > WarrantyVans)
AND (DateDiff("M",PurchaseDate,CURRENT_TIMESTAMP) > WarrantyVanMonths)
Should this work or are you not able to have a query like the above within the UPDATE statement?
Thanks for your help
You need to combine both into a single statement. I would also advise you start using table aliases to make your code a little more readable...
UPDATE v
SET WarrantyId = '1'
FROM tblGeneralVehicleInformation v
INNER JOIN tblModel mo
ON v.Model_IDFK = mo.Model_ID
INNER JOIN tblMake ma
ON v.Make_IDFK = ma.Make_ID
WHERE (mo.VanOrCar = N'Van')
AND (Mileage > WarrantyVans)
AND (DateDiff("M",PurchaseDate,CURRENT_TIMESTAMP) > WarrantyVanMonths)

How to create a query using Access from a given SQL

Someone gave me the following SQL and wants me to do a query using Access, so that it returns the information that they need. All dbo_**** are databases where they get the information from.
I tried to do the following SQL using a design view, but its not working, the datasheet(table) doesnt match the information.
I get lost in the lines LEFT OUTER JOIN ... I dont know what to do with anything after that. Can someone help me, please ?
Or if someone someone can edit the SQL so that it works on Access just copying in the SQL view mode.
Thank you.
Declare #data datetime
set #data = '2013-12-31'
--Fundos
SELECT
RelCliSFN.CdCrt,
MC5.Nome 'NomeCarteira',
MC5.CGC 'CNPJCarteira',
player_adm.NomeCurto 'Administrador',
RelCliSFN.Cliente,
CE5.Nome 'NomeCliente',
CE5.CPFCGC 'CPF/CNPJCliente',
VigRelCliSFN.DtIni,
VigRelCliSFN.DtFim
FROM
RelCliSFN
Inner JOIN MC5 ON MC5.Carteira = RelCliSFN.CdCrt
INNER JOIN MC5Auxiliar ON MC5.Carteira = MC5Auxiliar.Carteira
Inner Join VigRelCliSFN ON RelCliSFN.IdRelCliSFN = VigRelCliSFN.IdRelCliSFN
Inner Join CE5 ON CE5.Cliente=RelCliSFN.Cliente
LEFT OUTER JOIN PlayAdmxMC5 ON MC5.Carteira = PlayAdmxMC5.CdCrt AND PlayAdmxMC5.DtIniVig =
(SELECT MAX(DtIniVig) FROM PlayAdmxMC5 WHERE MC5.Carteira = CdCrt AND DtIniVig < MC5.DataAtual)
INNER JOIN Player player_adm ON PlayAdmxMC5.IdPlayAdm = player_adm.ID
WHERE
--MC5Auxiliar.bNaoExpCCSFN is null
((VigRelCliSFN.DtIni <= #data)
and ((VigRelCliSFN.DtFim >= #data) or (VigRelCliSFN.DtFim is null)))
and MC5.CGC <> 0
and CE5.Assessor not in (17, 99)
and CE5.CPFCGC <>0
and MC5.TipoCarteira <> 4
--and RelCliSFN.CdCrt = 3`
As the others already mentioned, your query has MS SQL-Server syntax. So there are three ways you could solve your problem.
Solution 1:
Create a view in the SQL-Server database.
To do this, open your SQL-Server Management Studio. Go to YourServer > databases > YourDatabase > views. Right click on "views" and then select "new view...". Close the "add table" window. Copy your sql-code into the sql window (the one saying "SELECT FROM"). You will get an error message saying that your code can't be displayed. Ignore it. Save your view. You can connect it to your Access database the same way you would connect a table.
Solution 2:
Use a SQL-Passthrough query in Access.
This is a bit complicated to explain, because almost every Access version has a slightly different menu. I'll explain it for Access 2007.
Create a new query. Close the "add table" window. Choose "Pass-Through" from the design menu (I don't know exactly if the menu label of the english version is "design". In my version it says "Entwurf"). Open the properties window. Insert the correct ODBC string. The easiest way to get an ODBC-string is to use one from an existing ODBC-table. Go to the VBA immediate window (Ctrl + G) and write ?CurrentDb.TableDefs("YourTable").Connect (instead of YourTable you have to insert the name of your ODBC-table). Press Return. You should get something like
ODBC;DSN=YourConnection;Description=IAmAnODBCConnection;APP=2007 Microsoft Office system;DATABASE=YourDatabase
Copy this string into the ODBC property of your query. Be sure the option "returns records" is set to "Yes". Copy you SQL into the query and save it.
Solution 3:
Convert your SQL Server syntax to Access syntax. Before doing this, you have to connect every table which is used in the query. I can't test my syntax conversion, but this should work:
PARAMETERS data DateTime = #2013-12-31#;
SELECT
RelCliSFN.CdCrt,
MC5.Nome "NomeCarteira",
MC5.CGC "CNPJCarteira",
player_adm.NomeCurto "Administrador",
RelCliSFN.Cliente,
CE5.Nome "NomeCliente",
CE5.CPFCGC "CPF/CNPJCliente",
VigRelCliSFN.DtIni,
VigRelCliSFN.DtFim
FROM
RelCliSFN
Inner JOIN MC5 ON MC5.Carteira = RelCliSFN.CdCrt
INNER JOIN MC5Auxiliar ON MC5.Carteira = MC5Auxiliar.Carteira
Inner Join VigRelCliSFN ON RelCliSFN.IdRelCliSFN = VigRelCliSFN.IdRelCliSFN
Inner Join CE5 ON CE5.Cliente=RelCliSFN.Cliente
LEFT OUTER JOIN PlayAdmxMC5 ON MC5.Carteira = PlayAdmxMC5.CdCrt AND PlayAdmxMC5.DtIniVig =
(SELECT MAX(DtIniVig) FROM PlayAdmxMC5 WHERE MC5.Carteira = CdCrt AND DtIniVig < MC5.DataAtual)
INNER JOIN Player player_adm ON PlayAdmxMC5.IdPlayAdm = player_adm.ID
WHERE
((VigRelCliSFN.DtIni <= [data])
and ((VigRelCliSFN.DtFim >= [data]) or (VigRelCliSFN.DtFim is null)))
and MC5.CGC <> 0
and CE5.Assessor not in (17, 99)
and CE5.CPFCGC <>0
and MC5.TipoCarteira <> 4
Well I don't know if Access can handle the equation of PlayAdmxMC5.DtIniVig = (Subquery). If it doesn't work, you should create a new query containing only the subquery and then connect it to this query.
MAIN CODE I am using
SELECT dbo_RelCliSFN.CdCrt, dbo_MC5.Nome AS NomeCarteira, dbo_MC5.CGC AS CNPJCarteira, dbo_RelCliSFN.Cliente, dbo_CE5.Nome AS NomeCliente, dbo_CE5.CPFCGC AS [CPF/CNPJCliente], dbo_VigRelCliSFN.DtIni, dbo_VigRelCliSFN.DtFim
FROM ((((dbo_RelCliSFN INNER JOIN dbo_CE5 ON dbo_RelCliSFN.Cliente = dbo_CE5.Cliente) INNER JOIN dbo_MC5 ON dbo_RelCliSFN.CdCrt = dbo_MC5.Carteira) INNER JOIN dbo_MC5Auxiliar ON dbo_MC5.Carteira = dbo_MC5Auxiliar.Carteira) INNER JOIN dbo_VigRelCliSFN ON dbo_RelCliSFN.IdRelCliSFN = dbo_VigRelCliSFN.IdRelCliSFN) LEFT JOIN Query1 ON dbo_MC5.Carteira = Query1.CdCrt
GROUP BY dbo_RelCliSFN.CdCrt, dbo_MC5.Nome, dbo_MC5.CGC, dbo_RelCliSFN.Cliente, dbo_CE5.Nome, dbo_CE5.CPFCGC, dbo_VigRelCliSFN.DtIni, dbo_VigRelCliSFN.DtFim, dbo_MC5.TipoCarteira, dbo_CE5.Assessor
HAVING (((dbo_RelCliSFN.CdCrt)=802) AND ((dbo_MC5.CGC)<>0) AND ((dbo_CE5.CPFCGC)<>0) AND ((dbo_VigRelCliSFN.DtIni)<=#12/31/2013#) AND ((dbo_VigRelCliSFN.DtFim)>=#12/31/2013# Or (dbo_VigRelCliSFN.DtFim) Is Null) AND ((dbo_MC5.TipoCarteira)<>4) AND ((dbo_CE5.Assessor) Not In (17.19)));

Linked Server in SQL Server 2008

Newbie. Be gentle (or parental)
I have a query that I'm trying to build for a report. From instance AWDATA (SQL Server 2008), I have a linked server GGIAPP01 (which contains an ACCPAC database).
When I run the following, with lines commented out, all is well.
When I uncomment, I get no argument, the query runs, BW_AK.NR_RECHNUNG, BW_AP.ID, BW_AS.POS_NR are returned as NULL.
Also BW_AUFTR_KOPF is one to many BW_AUFTR_POS, and BW_AUFTR_POS is one to many BW_AUFTR_STKL, but the record count remains the same regardless.
I suspect the first (BW) join is the culprit, but I'm not sure how to verify exactly. Without the CAST, I get a type mismatch, as IDINVC is char(22) and NR_RECHNUNG is int.
Any feedback is appreciated. This is a new domain for me!
Thank you,
Matt
declare #FiscalPeriod integer = 03, #FiscalYear integer = 2014
select
AROBP.IDINVC, AROBP.AMTPAYMTC, AROBP.TRANSTYPE, AROBP.TRXTYPE,
AROBP.FISCPER, AROBP.FISCYR, AROBP.DATEBTCH, AROBP.IDCUST,
ARCUS.NAMECUST,
ARIBH.TEXTTRX, ARIBH.DATEINVC, ARIBH.AMTINVCTOT,
ARSAP.NAMEEMPL,
-- BW_AK.NR_RECHNUNG,
-- BW_AP.ID,
-- BW_AS.POS_NR
from GGIAPP01.GGI.dbo.AROBP AROBP
left join GGIAPP01.GGI.dbo.ARCUS ARCUS on AROBP.IDCUST = ARCUS.IDCUST
left join GGIAPP01.GGI.dbo.ARIBH ARIBH on AROBP.IDINVC = ARIBH.IDINVC
left join GGIAPP01.GGI.dbo.ARSAP ARSAP on ARCUS.CODESLSP1 = ARSAP.CODESLSP
--left join GGIMAIN.SYSADM.BW_AUFTR_KOPF BW_AK on AROBP.IDINVC = CAST(BW_AK.NR_RECHNUNG as
--varchar)
--left join GGIMAIN.SYSADM.BW_AUFTR_POS BW_AP on BW_AK.ID = BW_AP.ID
--left join GGIMAIN.SYSADM.BW_AUFTR_STKL BW_AS on BW_AP.ID = BW_AS.ID and BW_AP.POS_NR =
--BW_AS.POS_NR
where AROBP.IDINVC NOT LIKE 'PY%'
AND AROBP.FISCPER = #FiscalPeriod
AND AROBP.FISCYR = #FiscalYear
order by AROBP.IDINVC, ARSAP.NAMEEMPL, AROBP.IDCUST

Joining on a many to many relationship with LINQ

I have been tasked with converting some old SQL stored procs to LINQ for an EF migration we are doing and Im a little stumped. Given that this is a migration from an existing application the edmx was generated database first. So, I have a SQL statement that I am trying to replicate:
SELECT DISTINCT
d.DeliverySubscriptionId
, d.ContactId
, d.statementMacroId_fk
, m.Name as MacroName
, DeliveryMethod = REPLACE((SELECT DISTINCT
dm2.Name + ',' AS 'data()'
FROM
DeliverySubscription d2
JOIN
StatementMacro m2 on
d2.StatementMacroId_fk = m2.StatementMacroId
JOIN
DeliverySubscription_Method_Rel dmr2 ON
d2.DeliverySubscriptionId = dmr2.DeliverySubscriptionId_Fk
JOIN
dbo.DeliveryMethod dm2 ON
dmr2.DeliveryMethodId_Fk = dm2.DeliveryMethodId
WHERE
d.DeliveryConfigurationId_fk = #configurationId
AND
d.IsActive = 1
AND
D.DeliverySubscriptionId = D2.DeliverySubscriptionId FOR XML PATH('')) + '$', ',$', '')
FROM
DeliverySubscription d
INNER JOIN
StatementMacro m ON
d.StatementMacroId_fk = m.StatementMacroId
JOIN
DeliverySubscription_Method_Rel dmr ON
d.DeliverySubscriptionId = dmr.DeliverySubscriptionId_Fk
JOIN dbo.DeliveryMethod dm ON
dmr.DeliveryMethodId_Fk = dm.DeliveryMethodId
WHERE
d.DeliveryConfigurationId_fk = #configurationId
AND
d.IsActive = 1
In particular the part that I have having an issue with is the JOIN DeliverySubscription_Method_Rel which is a relationship table representing a many to many relationship between DeliverySubscription and DeliveryMethod.
This shows up as:
[DeliverySubscription] * ---- * [Delivery Method]
in the database diagram in the edmx. No DeliverySubscription_Method_Rel entity is created. As you can see in the SQL statement the JOIN is directly on the relationship table, but I cant seem to figure out how to replicate this in LINQ. Please help!
UPDATE:
So looking around the web I found a similar example which suggested doing something like this:
from s in Context.DeliverySubscriptions
from dm in s.DeliveryMethods
join sm in Context.StatementMacroes on s.StatementMacroId_Fk equals sm.StatementMacroId
where s.DeliveryConfigurationId_Fk == configurationId
select new DeliverySubscription_dto
{
DeliverySubscriptionId = s.DeliverySubscriptionId,
QubeContactId = s.QubeContactId,
statementMacroId_fk = s.StatementMacroId_Fk,
MacroName = sm.Name,
DeliveryMethod = dm.Name.Replace("$","").Replace(",$","")
}
...however because I still have a lot of other things to change in the application thus far I am unable to build in order to test this yet so I just wanted to run this buy you all to see if this seems correct.
That query is a beast. If you weren't having any performance problems with it, I would probably just add it to the datamodel and use linq/EF to call it.