SQL Update Column from another Table - sql-server

So I have two tables called "MasterTracker" and "CapitalEdge."
I want to update the column "CompanyName" in MasterTracker to equal the table "Target name" in CapitalEdge but only when another column in CapitalEdge, called "Deal Stage" equals "1.0 Prospect"
I know that 44 lines should be updated but I get a popup that says only 32 are being updated.
Also, when I do run the code, nothing actually updates. I am writing this in Microsoft Access if that makes a difference.
Any help would be greatly appreciated.
Here is the code I am running:
update MasterTracker
left
join CapitalEdge on CapitalEdge.[Target name] = MasterTracker.[Companyname]
set MasterTracker.[CompanyName] = CapitalEdge[Target name]
where CapitalEdge.[Deal Stage] = "1.0 Prospect";

I do not have access to test this on, so this code is untested, but raw SQL could be this:
update MasterTracker
set CompanyName = CE.[Target Name]
from MasterTracker MT
join CapitalEdge CE on CE.[Target Name] = MT.CompanyName and CE.[Deal Stage] = '1.0 Prospect'

Related

Cannot input parameters in SQL code for MS query

I'm creating an Excel report, which other users beside myself could manage.
At the moment I'm struggling with creating the parameters in MS Query, so that they would get the input from a cell in Excel.
Everytime I try to paste my code, where I have changed the original dates with the "question marks" I get the following error.
"Parameters are not allowed in queries that can't be displayed grpahically."
I have tried to create parameters for very simple queries. Like
select *
From dmbase.test
where ID = ?
And there the parameters work, I could add even 10 or more and it would still work.
In addition I have tried to paste the code as it is in SSMS and then later through Data-Properties->Query Properties ->Definitions to change the code and add parameters to the "Command Text" box, but Excel just gives an error.
Also tried to declare variables for my parameters, but that didn't work as well. Gave an error regarding symbols.
declare Parameter1 date(10)
set Parameter1 = ?
declare Parameter2 date(10)
set Parameter2 = ?
I'm not 100% sure that the joins are to blame, but that's my feeling.
My code can be seen below.
select
loc.LocationLang
,loc.DistrictLang
,loc.InventoryRegionLang
,cod.ContractNumber
,cus.CustomerLang
,cus.InternalCustomerType
,cus.CustomerGroupCode
,cus.Organizationalcode
,css.CustomerSubSegmentLang
,loc.AnalysisRegionLang
,dht.ContractHeaderTypeLang
,cod.RentalOutDate
from
dmbase.fContractOpenDetail as cod
left join dmbase.dLocation as loc
on cod.LocationID = loc.LocationID
left join dmbase.dCustomer as cus
on cod.CustomerID = cus.CustomerID
left join dmbase.dCustomerSubSegment as css
on cus.CustomerSubsegmentID = css.CustomerSubSegmentID
left join dmbase.dContractHeaderType as dht
on cod.ContractHeaderTypeAMID = dht.ContractHeaderTypeAMID
where
cod.CompanyID = '6'
and cod.RentalOutDate between ? and ?
and left(loc.LocationLang,4) = '7201'
order by cod.ContractNumber
I would appreciate if you could say, how I could put parameters in so that I would not get the error of "Parameters are not allowed...".

SQL Duplicate column names error in Create View, even with aliases

The error is oddly specific, but I've just about honed in where it's occurring. The standard fix doesn't seem to be working though.
Here's where the error occurs. It's a big statement, so I'm just posting where I've found the error
CREATE OR REPLACE VIEW SalesInvoiceDoc
AS
( SELECT si.salinv_Num, si.salinv_Terms, si.salinv_SaleDate,
es.empName AS SalesAgent, man.empName AS ApprovingManager,
si.salinv_ApproveDate, ...
... FROM service_invoice si
JOIN employee es
ON (es.empID = si.salinv_EmpID)
JOIN employee man
ON (man.empID = si.salinv_ManID)
Essentially it's a Sales invoice document with a sales agent and approving manager. Both are stored in the employee table with a subtype discriminator set up for 'manager' or 'sales', and views for the subtype children tables to avoid duplication errors.
I've supplied aliases to try and avoid duplicate columns, but when I run this script, I get the duplicate column names error:
ORA-00957: duplicate column name
Does anyone know how to resolve this? Is it even possible? Any help would be greatly appreciated. Thank you in advance!
Edit: here's the full statement
CREATE OR REPLACE VIEW SalesInvoiceDoc
AS
( SELECT si.salinv_Num, si.salinv_Terms, si.salinv_SaleDate,
es.empName AS SalesAgent,
man.empName AS ApprovingManager, si.salinv_ApproveDate,
sc.custName, sc.custHouse, sc.custCity,
sc.custState, sc.custZIP, sc.custPhone, sc.custEmail,
sv.vehicle_VIN, sv.vehicle_year, sv.vehicle_make,
sv.vehicle_model, sv.vehicle_ext_color, sv.vehicle_trim,
sv.vehicle_list_base_price, sv.vehicle_mileage, sv.vehicle_condition,
sv.vehicle_description,
ti.vehicle_make, ti.vehicle_year, ti.vehicle_model, ti.vehicle_VIN,
ti.tradein_allowance,
sv.vehicle_list_base_price "SellingPrice", sv.shipping "Shipping",
ti.tradein_allowance "TradeAllowance",
(sv.vehicle_list_base_price + sv.shipping - ti.tradein_allowance) "Subtotal",
(sv.vehicle_list_base_price + sv.shipping - ti.tradein_allowance)*.0825 "Taxes",
(sv.vehicle_list_base_price + sv.shipping - ti.tradein_allowance)*1.0825 "TotalSellingPrice"
FROM sales_invoice si
JOIN employee es
ON (es.empID = si.salinv_EmpID)
JOIN employee man
ON (man.empID = si.salinv_ManID)
JOIN customer sc
ON (sc.custID = si.salinv_CustID)
JOIN vehicle sv
ON (sv.vehicle_VIN = si.salinv_SalVIN)
LEFT OUTER JOIN vehicle ti
ON (ti.vehicle_VIN = si.salinv_tiVIN)
);
You are duplicating column names from 2 different tables:
sv.vehicle_VIN,
sv.vehicle_year,
sv.vehicle_make,
sv.vehicle_model
and
ti.vehicle_make,
ti.vehicle_year,
ti.vehicle_model,
ti.vehicle_VIN
The resulting column name does not include the table alias.
Issue is cause sv.vehicle_VIN is appearing twice in your query and so does other columns. See below. You need to alias them all accordingly
**sv.vehicle_VIN**, **sv.vehicle_year**, **sv.vehicle_make**, **sv.vehicle_model**,
**ti.vehicle_make**, **ti.vehicle_year**, **ti.vehicle_model**, **ti.vehicle_VIN**,

Source data type "200" not found error when exporting query results to excel Microsoft SQL Server 2012

I am very new to Microsoft SQL Server and am using 2012 Management Studio. I get the error above when I try to export query results to an excel file using the wizard. I have seen solutions posted elsewhere for this error but do not know enough to figure out how to implement the solutions recommended. Can somebody please walk me through one of these solutions step by step?
I believe my problem is that the SQL Server Import and Export Wizard Does Not Recognise Varchar and NVarchar which I believe is the data type for the columns that I am receiving errors for.
Source Type 200 in SQL Server Import and Export Wizard?
http://connect.microsoft.com/SQLServer/feedback/details/775897/sql-server-import-and-export-wizard-does-not-recognise-varchar-and-nvarchar#
Query:
SELECT licenseEntitlement.entID, licenseEntitlement.entStartDate, entEndDate, quote.quoteId, quote.accountId, quote.clientId, quote.clientName, quote.contactName,
quote.contactEmail, quote.extReference, quote.purchaseOrderNumber, quote.linkedTicket
FROM licenseEntitlement INNER JOIN
quote ON quote.quoteId = SUBSTRING(licenseEntitlement.entComments, 12, PATINDEX('% Created%', licenseEntitlement.entComments) - 12)
inner join sophos521.dbo.computersanddeletedcomputers on computersanddeletedcomputers.name = entid and IsNumeric(computersanddeletedcomputers.name) = 1
WHERE (licenseEntitlement.entType = 'AVS') AND (licenseEntitlement.entComments LIKE 'OV Order + %') and entenddate < '4/1/2014'
ORDER BY licenseEntitlement.entEndDate
Error:
TITLE: SQL Server Import and Export Wizard
------------------------------
Column information for the source and the destination data could not be retrieved, or the data types of source columns were not mapped correctly to those available on the destination provider.
[Query] -> `Query`:
- Column "accountId": Source data type "200" was not found in the data type mapping file.
- Column "clientId": Source data type "200" was not found in the data type mapping file.
- Column "clientName": Source data type "200" was not found in the data type mapping file.
- Column "contactName": Source data type "200" was not found in the data type mapping file.
- Column "contactEmail": Source data type "200" was not found in the data type mapping file.
- Column "extReference": Source data type "200" was not found in the data type mapping file.
- Column "purchaseOrderNumber": Source data type "200" was not found in the data type mapping file.
- Column "linkedTicket": Source data type "200" was not found in the data type mapping file.
If any more details are needed please let me know
So, implementing the suggestion at the StackOverflow link you gave, of turning the query into a View, here's an example of what that could look like (with some code formatting ;) --
CREATE VIEW [dbo].[test__View_1]
AS
SELECT LIC.entID, LIC.entStartDate, entEndDate,
quote.quoteId, quote.accountId, quote.clientId, quote.clientName,
quote.contactName, quote.contactEmail, quote.extReference,
quote.purchaseOrderNumber, quote.linkedTicket
FROM [dbo].licenseEntitlement LIC WITH(NOLOCK)
INNER JOIN [dbo].quote WITH(NOLOCK)
ON quote.quoteId = SUBSTRING(LIC.entComments, 12,
PATINDEX('% Created%', LIC.entComments) - 12)
INNER JOIN sophos521.dbo.computersanddeletedcomputers COMPS WITH(NOLOCK)
ON COMPS.name = entid and IsNumeric(COMPS.name) = 1
WHERE (LIC.entType = 'AVS')
AND (LIC.entComments LIKE 'OV Order + %')
and (entenddate < '4/1/2014')
ORDER BY LIC.entEndDate
GO
Then, you would export from test__View_1 (or whatever real name you choose for it), as if test__View_1 was the table name.
FYI, after the first time you've executed the above -- after you've "created" the view -- then from then on, the view's first line (during modifications) changes, from CREATE VIEW, to ALTER VIEW.
((And, aside from the bug question... in your WHERE clause, did you intend entComments LIKE 'OV Order + %', or was that really intended to be entComments LIKE 'OV Order%'? I've made that change, in the alternative example code, below.))
Note: if you're going to be exporting repeatedly (or re-using) the output from one run, and especially if your query is slow or hogs the machine... then instead of a VIEW, you might prefer a SELECT INTO, to create a table once, which can be quickly re-used. (I would also choose SELECT INTO rather than CREATE VIEW, when developing a one-time-only query for export.)
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'zz_LIC_ENT_DETAIL')
DROP TABLE [dbo].zz_LIC_ENT_DETAIL
SELECT LIC.entID, LIC.entStartDate, LIC.entEndDate,
quote.quoteId, quote.accountId, quote.clientId, quote.clientName,
quote.contactName, quote.contactEmail, quote.extReference,
quote.purchaseOrderNumber, quote.linkedTicket
INTO [dbo].zz_LIC_ENT_DETAIL
FROM [dbo].licenseEntitlement LIC WITH(NOLOCK)
INNER JOIN [dbo].quote WITH(NOLOCK)
ON quote.quoteId = SUBSTRING(LIC.entComments, 12,
PATINDEX('% Created%', LIC.entComments) - 12)
INNER JOIN sophos521.dbo.computersanddeletedcomputers COMPS WITH(NOLOCK)
ON COMPS.name = LIC.entid and IsNumeric(COMPS.name) = 1
WHERE (LIC.entType = 'AVS')
AND (LIC.entComments LIKE 'OV Order%')
and (LIC.entenddate < '4/1/2014')
ORDER BY LIC.entEndDate
Then, you would of course export from table zz_LIC_ENT_DETAIL (or whatever table name you chose).
Hope that helps...
It might be easier to right click query results window and choosing Save Results As (CSV)..
To append the column names in the first row you'd also need to modify your query in this way (note the cast for int or datetime columns):
select 'col1', 'col2', 'col3'
union all
select cast(id as varchar(10)), name, cast(someinfo as varchar(28))
from Question1355876

Update on linked server with nested subquery

I want to update on a linked server the result of a query as well from a linked server.
The first sql snippet gives me the value to be updated:
SELECT mmdb_vessel.IMONo, mmdb_vessel.DeathDate
From OPENQUERY(MMDB, 'SELECT FunctionalLocation, IMONo, VesselStatus, CONVERT(VARCHAR(10), DeathDate, 102) AS DeathDate
FROM VESSEL
WHERE VESSEL.VesselStatusID <> 42 AND VESSEL.DeathDate is not null') as mmdb_vessel
, eb_all_v
WHERE
eb_all_v.IMO_No = mmdb_vessel.IMONo
AND eb_all_v.status = 'in service'
the second is actually what I'm not able to implement, it should show what I want to achieve:
UPDATE EPI2..EPI.PLANT
SET KIND_OF_LIQUIDATION_NO = 1
, LIQUIDATION_DATE = [result from snippet above].DeathDate
Where EPI2..EPI.PLANT.IMONo = [result from snippet above].IMONo
I'm not so sure if my explanation is sufficient, please feel free to ask for additional information!
Thanks, already in advance,
Werner
I would recommend to select the data from the remote server first and store the required data e.g. in a temptable, because LinkedServer and updates can have some sideeffects (e.g. performing a tablescan on the remote table, altough you would not expect it if an updaet is involved, etc) - but this depends on your exact usage/scenario.
Select data you need to update
SELECT * INTO #tmpTable FROM LINKEDSERVER.EPI.dbo.PLANT WHERE ....
Perform the update on local server
UPDATE EPI2..EPI.PLANT SET KIND_OF_LIQUIDATION_NO = 1, LIQUIDATION_DATE = t.DeathDate FROM #tmpTable t INNER JOIN EPI2..EPI.PLANT p on t.IMONo = p.IMONo

How to do Sql Server CE table update from another table

I have this sql:
UPDATE JOBMAKE SET WIP_STATUS='10sched1'
WHERE JBT_TYPE IN (SELECT JBT_TYPE FROM JOBVISIT WHERE JVST_ID = 21)
AND JOB_NUMBER IN (SELECT JOB_NUMBER FROM JOBVISIT WHERE JVST_ID = 21)
It works until I turn it into a parameterised query:
UPDATE JOBMAKE SET WIP_STATUS='10sched1'
WHERE JBT_TYPE IN (SELECT JBT_TYPE FROM JOBVISIT WHERE JVST_ID = #jvst_id)
AND JOB_NUMBER IN (SELECT JOB_NUMBER FROM JOBVISIT WHERE JVST_ID = #jvst_id)
Duplicated parameter names are not allowed. [ Parameter name = #jvst_id ]
I tried this (which i think would work in SQL SERVER 2005 - although I haven't tried it):
UPDATE JOBMAKE
SET WIP_STATUS='10sched1'
FROM JOBMAKE JM,JOBVISIT JV
WHERE JM.JOB_NUMBER = JV.JOB_NUMBER
AND JM.JBT_TYPE = JV.JBT_TYPE
AND JV.JVST_ID = 21
There was an error parsing the query. [ Token line number = 3,Token line offset = 1,Token in error = FROM ]
So, I can write dynamic sql instead of using parameters, or I can pass in 2 parameters with the same value, but does someone know how to do this a better way?
Colin
Your second attempt doesn't work because, based on the Books On-Line entry for UPDATE, SQL CE does't allow a FROM clause in an update statement.
I don't have SQL Compact Edition to test it on, but this might work:
UPDATE JOBMAKE
SET WIP_STATUS = '10sched1'
WHERE EXISTS (SELECT 1
FROM JOBVISIT AS JV
WHERE JV.JBT_TYPE = JOBMAKE.JBT_TYPE
AND JV.JOB_NUMBER = JOBMAKE.JOB_NUMBER
AND JV.JVST_ID = #jvst_id
)
It may be that you can alias JOBMAKE as JM to make the query slightly shorter.
EDIT
I'm not 100% sure of the limitations of SQL CE as they relate to the question raised in the comments (how to update a value in JOBMAKE using a value from JOBVISIT). Attempting to refer to the contents of the EXISTS clause in the outer query is unsupported in any SQL dialect I've come across, but there is another method you can try. This is untested but may work, since it looks like SQL CE supports correlated subqueries:
UPDATE JOBMAKE
SET WIP_STATUS = (SELECT JV.RES_CODE
FROM JOBVISIT AS JV
WHERE JV.JBT_TYPE = JOBMAKE.JBT_TYPE
AND JV.JOB_NUMBER = JOBMAKE.JOB_NUMBER
AND JV.JVST_ID = 20
)
There is a limitation, however. This query will fail if more than one row in JOBVISIT is retuned for each row in JOBMAKE.
If this doesn't work (or you cannot straightforwardly limit the inner query to a single row per outer row), it would be possible to carry out a row-by-row update using a cursor.

Resources