Proper way to use table alias in linked server update query? - sql-server

I'm attempting to write an update query that uses both a local server and a linked server (amazon web service sql server). I need to use a table alias in order to truncate my statements to 4 denominations or less, such as [Server].[Database].[TableAlias].[Column] instead of [Server].[Database].[Owner].[Table].[Column] so that the multi-part identifier can be bound.
This is the update query I am attempting to use table aliases with:
UPDATE [Amazon IP].[AmazonDatabase].dbo.InkVials
SET InkRequestID = Local_Database.dbo.TasksInkRequests.InkRequestID
FROM Local_Database.dbo.TasksInkRequests
WHERE [Amazon IP].[AmazonDatabase].dbo.InkVials.InkRequestID = Local_Database.dbo.TasksInkRequests.JobRequestID
AND [Amazon IP].[AmazonDatabase].dbo.InkVials.Processing = 1;
I've tried multiple ways but don't seem to be doing it right.

This is normally how you use Table aliases to do an update with a joined table:
UPDATE i
SET InkRequestID = r.InkRequestID
FROM [Amazon IP].[AmazonDatabase].dbo.InkVials i
INNER JOIN Local_Database.dbo.TasksInkRequests r
ON i.InkRequestID = r.JobRequestID
WHERE i.Processing = 1;

Related

R : problem with the dplyr::tbl() function due to restricted permission

I work with large databases that needs to be stored into a server.
So, to work with them on Rstudio I have to open a connection to my Microsoft SQL Server with the dbConnect function :
conn <- dbConnect(odbc(),"myconnection",uid="***",pwd="***",schema="dbo",access="readonly")
and in order to use dplyr, I have to create data references with the tbl function :
data <- tbl(conn, "data")
But one of the online dataframe contains a columns that I can't read because I dont have the access, but I can read everything else.
The SQL query behind the tbl() function is :
SELECT * FROM data
and this is my problem.
Even when I try to select a specific column it doesn't work (see below), so I can't create my references and I can't work.
select(tbl(conn, "data"), "columnX")
=
SELECT columnX FROM data
I think this is the tbl() function and the call of "SELECT *" that blocks me.
Do you know what can I do ? Is there smilar functions that could resolve my problem ?
If you know the columns that you have access to, then one option is to bypass the default access SELECT * FROM ... with your own SQL query.
A remote table is defined by two components:
The database conneciton
The query to the database
When you connect with the default approach tbl(conn, 'data') then it defaults to a query SELECT * FROM data.
But here is another approach:
custom_query = 'SELECT columnX FROM data'
remote_table = tbl(conn, dbplyr::sql(customer_query))

"The column prefix '*' does not match with a table name or alias name used in the query." while using a temp table

In a SQL Server 2000 stored procedure, I'm trying to perform an update statement to a table variable. It is currently giving me the error: "The column prefix 'WST' does not match with a table name or alias name used in the query."
UPDATE WST
SET
WST.QtySold = (SELECT SUM(II.QtyShipped)
FROM #InvoiceItems II
WHERE II.InvoiceDate >= WST.StartDate
AND II.InvoiceDate <= WST.EndDate),
WST.TotalSales = (SELECT SUM(ISNULL(II.QtyShipped, 0) * ISNULL(II.UnitPrice, 0))
FROM #InvoiceItems II
WHERE II.InvoiceDate >= WST.StartDate
AND II.InvoiceDate <= WST.EndDate),
WST.TotalCost = (SELECT SUM(ISNULL(II.QtyShipped, 0) * ISNULL(II.UnitCost, 0))
FROM #InvoiceItems II
WHERE II.InvoiceDate >= WST.StartDate
AND II.InvoiceDate <= WST.EndDate)
FROM #WeeklySalesTrend WST
WHERE WST.WeekNo = 1
This error only appeared after I created the temp table #InvoiceItems and replaced the Inner Join of two tables with the temp table. Why would changing the two-table inner join out for a temp table cause this error and how do I fix/get around it?
I don't have a SQL 2000 box to test this on but I think your query syntax is correct. I suspect there may be invisible control characters that's messing up the parsing. This used to happen from time to time but I haven't seen the issue for a while. Try typing the query into a new query window from scratch.
The answer boils down to this, SQL Query Analyzer gave me the wrong location for the error. The error was actually because of an Insert statement 17 lines higher in the code where I was trying to use WST when I never aliased it up there. I don't know if this was a glitch/bug on Query Analyzer's side or if the stored procedure optimized to more lines and there its location was off. Either way, the problem has been fixed. Thanks for the suggestions and quick responses though and sorry for wasting your time.

How to constrain SQL tables to multiple specific types

I have a small database that I'm developing SQL Server 2008.
I don't have much SQL experience overall, so finding it difficult to find information as to what the appropriate pattern for this issue is.
The main table is 'Provider' a Provider can be a 'MatchService', a 'CompareService', or both depending on 'ProviderTypeId'. I'm looking to contrain data in the MatchService and CompareService tables based on the following rules:
1) A Provider with a ProviderTypeId = Lender can be both a MatchService and a CompareService;
2) A Provider with a ProviderTypeId = Pingtree can only be a MatchService.
I know that a solution probably includes a bridge table in the schema but I'm unsure as to what and where. Any advice appreciated.
Maby something like this:
CREATE TRIGGER MatchService_ITrig
ON MatchService
FOR INSERT
AS
IF NOT EXISTS (
SELECT
ProviderID
FROM
Provider p
INNER JOIN
inserted i ON
P.ID = I.ProviderID
WHERE
ProviderTypeID = 'Lender' OR
ProviderTypeID = 'PingTree'
)
BEGIN
ROLLBACK TRANSACTION
END
How about :
ALTER TABLE CompareService
ADD CONSTRAINT chkPTID CHECK (ProviderTypeId = Lender);
GO
Raj

SQL Server Linked Server

All,
I am trying out a new linked server - I can run this command fine:
SELECT * FROM NextGen4.NGEPMWareHouse.dbo.Network_People
If I try to get fancy (update a table on my local server from the linked server)
UPDATE dbo.Network_People
SET dbo.Network_People.NGTimeStamp = NextGen4.NGEPMWareHouse.dbo.Network_People.[TimeStamp]
WHERE dbo.Network_People.HIN = NextGen4.NGEPMWareHouse.dbo.Network_People.HIN
I get
The number name 'NextGen4.NGEPMWareHouse.dbo.Network_People' contains more than the maximum number of prefixes. The maximum is 3.
Try woking with UPDATE … FROM and an alias.
UPDATE
dbo.Network_People
SET
NGTimeStamp = warehouse.[TimeStamp]
FROM
NextGen4.NGEPMWareHouse.dbo.Network_People AS warehouse
INNER JOIN dbo.Network_People AS people ON people.HIN = warehouse.HIN
Try to exclude ".dbo" prefix from your tablenames and use "update from"

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