Convert from SQL to XQuery
Hi there,
I am a total novice at XQuery. Please could someone convert the following SQL queries into XQuery form for me? I would be ever so greatfull.
The following SQL makes use of the Microsoft Northwind database.
--SQL QUERY 1
--postal address of all customers (for some kind of mail shot)
SELECT Customers.CompanyName, Customers.Address, Customers.City, Customers.[Postal Code], Customers.Country
FROM Customers
--SQL QUERY 2
--all order shipped in year 1997
SELECT Customers.CompanyName, Orders.OrderID, Orders.ShippedDate
FROM Customers, Orders
WHERE
((Customers.CustomerID) = (Orders.CustomerID))
AND ((Customers.CompanyName)="Around the Horn")
AND ((Orders.ShippedDate) between #12/31/996# AND #12/31/1997#)
--SQL QUERY 3
--all orders which shipped after their required arrival date (late!!)
SELECT Customers.CompanyName, Orders.OrderID
FROM Customers, Orders
WHERE
((Customers.CustomerID) = (Orders.CustomerID))
AND ((Orders.ShippedDate) > (Orders.RequiredDate))
--SQL QUERY 4
--all orders with item quantities of over 100 (bulk discount?)
SELECT Customers.CompanyName, Orders.OrderID, OrderDetails.Quantity
FROM Orders, [Order Details] as OrderDetails, Customers
WHERE Customers.CustomerID = Orders.CustomerID
AND Orders.OrderID = OrderDetails.OrderID
AND OrderDetails.Quantity > 100
--SQL QUERY 5
--apply discount to all orders from above query
update [Order Details] as OrderDetails
Set OrderDetails.Discount = OrderDetails.Discount * 1.05
where OrderDetails.OrderID in
select Orders.OrderID
from Orders, [Order Details] as OrderDetails, Customers
where Customers.CustomerID = Orders.CustomerID
AND Orders.OrderID = OrderDetails.OrderID
AND OrderDetails.Quantity > 100
)
A follow-up question ...
If the table tblmtk for example, there are three rows like this:
WC MPM Valid_from
34819 1 2010-06-01
34819 2.5 2011-01-01
34819 1.5 2012-01-01If the value is outside of the validity period (valid_from) shall it take the last valid_from value. How?
select max(MPM) keep(dense_rank first order by case when valid_from <= '2007-05-10' then valid_from else null end desc nulls last) r1
from tblmtk
where wc = '34819'I want the result to look like this:
R1= 1.5
But now I get R = 2.5
Similar Messages
-
How to convert from SQL Server table to Flat file (txt file)
I need To ask question how convert from SQL Server table to Flat file txt file
Hi
1. Import/Export wizened
2. Bcp utility
3. SSIS
1.Import/Export Wizard
First and very manual technique is the import wizard. This is great for ad-hoc and just to slam it in tasks.
In SSMS right click the database you want to import into. Scroll to Tasks and select Import Data…
For the data source we want out zips.txt file. Browse for it and select it. You should notice the wizard tries to fill in the blanks for you. One key thing here with this file I picked is there are “ “ qualifiers. So we need to make
sure we add “ into the text qualifier field. The wizard will not do this for you.
Go through the remaining pages to view everything. No further changes should be needed though
Hit next after checking the pages out and select your destination. This in our case will be DBA.dbo.zips.
Following the destination step, go into the edit mappings section to ensure we look good on the types and counts.
Hit next and then finish. Once completed you will see the count of rows transferred and the success or failure rate
Import wizard completed and you have the data!
bcp utility
Method two is bcp with a format file http://msdn.microsoft.com/en-us/library/ms162802.aspx
This is probably going to win for speed on most occasions but is limited to the formatting of the file being imported. For this file it actually works well with a small format file to show the contents and mappings to SQL Server.
To create a format file all we really need is the type and the count of columns for the most basic files. In our case the qualifier makes it a bit difficult but there is a trick to ignoring them. The trick is to basically throw a field into the
format file that will reference it but basically ignore it in the import process.
Given that our format file in this case would appear like this
9.0
9
1 SQLCHAR 0 0 """ 0 dummy1 ""
2 SQLCHAR 0 50 "","" 1 Field1 ""
3 SQLCHAR 0 50 "","" 2 Field2 ""
4 SQLCHAR 0 50 "","" 3 Field3 ""
5 SQLCHAR 0 50 ""," 4 Field4 ""
6 SQLCHAR 0 50 "," 5 Field5 ""
7 SQLCHAR 0 50 "," 6 Field6 ""
8 SQLCHAR 0 50 "," 7 Field7 ""
9 SQLCHAR 0 50 "n" 8 Field8 ""
The bcp call would be as follows
C:Program FilesMicrosoft SQL Server90ToolsBinn>bcp DBA..zips in “C:zips.txt” -f “c:zip_format_file.txt” -S LKFW0133 -T
Given a successful run you should see this in command prompt after executing the statement
Starting copy...
1000 rows sent to SQL Server. Total sent: 1000
1000 rows sent to SQL Server. Total sent: 2000
1000 rows sent to SQL Server. Total sent: 3000
1000 rows sent to SQL Server. Total sent: 4000
1000 rows sent to SQL Server. Total sent: 5000
1000 rows sent to SQL Server. Total sent: 6000
1000 rows sent to SQL Server. Total sent: 7000
1000 rows sent to SQL Server. Total sent: 8000
1000 rows sent to SQL Server. Total sent: 9000
1000 rows sent to SQL Server. Total sent: 10000
1000 rows sent to SQL Server. Total sent: 11000
1000 rows sent to SQL Server. Total sent: 12000
1000 rows sent to SQL Server. Total sent: 13000
1000 rows sent to SQL Server. Total sent: 14000
1000 rows sent to SQL Server. Total sent: 15000
1000 rows sent to SQL Server. Total sent: 16000
1000 rows sent to SQL Server. Total sent: 17000
1000 rows sent to SQL Server. Total sent: 18000
1000 rows sent to SQL Server. Total sent: 19000
1000 rows sent to SQL Server. Total sent: 20000
1000 rows sent to SQL Server. Total sent: 21000
1000 rows sent to SQL Server. Total sent: 22000
1000 rows sent to SQL Server. Total sent: 23000
1000 rows sent to SQL Server. Total sent: 24000
1000 rows sent to SQL Server. Total sent: 25000
1000 rows sent to SQL Server. Total sent: 26000
1000 rows sent to SQL Server. Total sent: 27000
1000 rows sent to SQL Server. Total sent: 28000
1000 rows sent to SQL Server. Total sent: 29000
bcp import completed!
BULK INSERT
Next, we have BULK INSERT given the same format file from bcp
CREATE TABLE zips (
Col1 nvarchar(50),
Col2 nvarchar(50),
Col3 nvarchar(50),
Col4 nvarchar(50),
Col5 nvarchar(50),
Col6 nvarchar(50),
Col7 nvarchar(50),
Col8 nvarchar(50)
GO
INSERT INTO zips
SELECT *
FROM OPENROWSET(BULK 'C:Documents and SettingstkruegerMy Documentsblogcenzuszipcodeszips.txt',
FORMATFILE='C:Documents and SettingstkruegerMy Documentsblogzip_format_file.txt'
) as t1 ;
GO
That was simple enough given the work on the format file that we already did. Bulk insert isn’t as fast as bcp but gives you some freedom from within TSQL and SSMS to add functionality to the import.
SSIS
Next is my favorite playground in SSIS
We can do many methods in SSIS to get data from point A, to point B. I’ll show you data flow task and the SSIS version of BULK INSERT
First create a new integrated services project.
Create a new flat file connection by right clicking the connection managers area. This will be used in both methods
Bulk insert
You can use format file here as well which is beneficial to moving methods around. This essentially is calling the same processes with format file usage. Drag over a bulk insert task and double click it to go into the editor.
Fill in the information starting with connection. This will populate much as the wizard did.
Example of format file usage
Or specify your own details
Execute this and again, we have some data
Data Flow method
Bring over a data flow task and double click it to go into the data flow tab.
Bring over a flat file source and SQL Server destination. Edit the flat file source to use the connection manager “The file” we already created. Connect the two once they are there
Double click the SQL Server Destination task to open the editor. Enter in the connection manager information and select the table to import into.
Go into the mappings and connect the dots per say
Typical issue of type conversions is Unicode to non-unicode.
We fix this with a Data conversion or explicit conversion in the editor. Data conversion tasks are usually the route I take. Drag over a data conversation task and place it between the connection from the flat file source to the SQL Server destination.
New look in the mappings
And after execution…
SqlBulkCopy Method
Sense we’re in the SSIS package we can use that awesome “script task” to show SlqBulkCopy. Not only fast but also handy for those really “unique” file formats we receive so often
Bring over a script task into the control flow
Double click the task and go to the script page. Click the Design script to open up the code behind
Ref.
Ahsan Kabir Please remember to click Mark as Answer and Vote as Helpful on posts that help you. This can be beneficial to other community members reading the thread. http://www.aktechforum.blogspot.com/ -
Migration Workbench is messing up data in converted from SQL Server image fields.
I am working on porting a SQL Server 7 database to Oracle 8i (8.1.6 release 2). In the SQL Server database I have several tables that contain image fields that hold binary data (like Word documents, and other files). When I port the database to Oracle, the data in these fields gets garbled (the resultant records contain the correct amount of data (bytes), yet the data is different). Data in image fields that contain text oriented data ports correctly (i.e. if you just saved a long string in the field). Has anyone else posted a similar problem? Is there a workaround here to get the data stored in these image fields to port correctly?
The thing is DDL of SQL Server and Oracle are quite different, without the help of MW from SQL Developer. You can't convert SQL server version of DDL to Oracle version. Of course you can accomplish the same thing using other tools like ERwin and Visio. Since SQL Developer is free why bother?
-
Error in Oracle 10 Procedure - converted from SQL Server
I have converted the folowing script from SQL Server proc to Oracle Proc; it compiles with a warning "30 Hint: Comparision with NULL in 'sp_MyEmployee'"
When this proc is executed; it generates an error "ORA-00900: invalid SQL statement"
Please help!
CREATE OR REPLACE PROCEDURE osp_DMEmployee(v_ahRole IN VARCHAR2 DEFAULT null,
v_Exclusion IN varchar2 DEFAULT null) as
v_MyString varchar2(32767);
v_spot NUMBER(5,0);
v_str varchar2(8000);
v_email varchar2(5000);
SWV_Exclusion varchar2(5000);
BEGIN
SWV_Exclusion := v_Exclusion;
v_MyString := 'SQLWAYS_EVAL# exprsnlid, dmdescription, dmregion, dmfieldloc, dmbusentity,
dmemployeenum, dmusername, dmtitle, dmemail, ahrole
FROM dm_Employee WHERE dmEmail is NOT NULL';
if v_ahRole is not NULL then
IF v_ahRole = 'PLANNER' then
v_MyString := v_MyString || 'SQLWAYS_EVAL# AND (DMTitle like ''%Coord%'' OR DMTitle like ''%Planner%'' OR DMTitle like ''%Svc Leader%'') ';
end if;
IF v_ahRole = 'TECHNICIAN' then
v_MyString := v_MyString || 'SQLWAYS_EVAL# ''' || v_ahRole || 'SQLWAYS_EVAL# is NOT NULL ';
end if;
IF v_ahRole = 'SUPERVISOR' then
v_MyString := v_MyString || 'SQLWAYS_EVAL# ''' || v_ahRole || 'SQLWAYS_EVAL# is NOT NULL ';
end if;
end if;
IF SWV_Exclusion is NOT NULL then
/* WHILE SUBSTR(CAST(SWV_Exclusion AS VARCHAR2),1,4000) <> '' LOOP */
WHILE SWV_Exclusion <> '' LOOP
v_spot := instr(SWV_Exclusion,',');
IF v_spot > 0 then
v_str := SUBSTR(SWV_Exclusion,1,v_spot -1);
SWV_Exclusion := SUBSTR(SWV_Exclusion,-(LENGTH(SWV_Exclusion) -v_spot));
ELSE
v_str := SWV_Exclusion;
SWV_Exclusion := '';
end if;
IF v_email is NOT NULL then
v_email := v_email || ',' || ' ''' || SUBSTR(v_str,1,100) || ''' ';
ELSE
v_email := ' ''' || SUBSTR(v_str,1,100) || ''' ';
end if;
END LOOP;
end if;
v_MyString := v_MyString || 'SQLWAYS_EVAL# IN (' || v_email || ')';
v_MyString := v_MyString || 'SQLWAYS_EVAL# ail';
DBMS_OUTPUT.PUT_LINE(SUBSTR(v_MyString,1,250));
EXECUTE IMMEDIATE v_MyString;
RETURN;
END;1) When discussing an error, please copy the actual error message. Usually you will get a line number to assist investigation;
2) Please refer to the FAQ (upper right corner of page) to show how to preserve code and make your question more readable;
3) Please ask the question in a forum that deals with the topic - such as "Database - General" (look for "Forum Home" link at top left of page)
4) Please note that the title of this forum is "Community Feedback and Suggestions (Do Not Post Product-Related Questions Here)"
(And ... did you display the SQL that you were attempting to execute. Execute Immediate is a last resort style of programming - not nice for most Oracle apps.) -
Convert from SQL server to Oracle?
How do I do this query in Oracle?
In SQL Server, it looks like this.
select
SELECT top 1 t1.mpm
FROM TblMtk T1
where t1.wc = '34819'
and t1.ValidFrom <= '2012-09-12'
order by t1.ValidFrom desc
) R1
SELECT top 1 t2.mpm
FROM TblMtk T2
where t2.wc = '34819'
order by t2.ValidFrom desc) R2A follow-up question ...
If the table tblmtk for example, there are three rows like this:
WC MPM Valid_from
34819 1 2010-06-01
34819 2.5 2011-01-01
34819 1.5 2012-01-01If the value is outside of the validity period (valid_from) shall it take the last valid_from value. How?
select max(MPM) keep(dense_rank first order by case when valid_from <= '2007-05-10' then valid_from else null end desc nulls last) r1
from tblmtk
where wc = '34819'I want the result to look like this:
R1= 1.5
But now I get R = 2.5 -
Convert from SQL 7.0 to ORACLE 8.0
Is the the workbench available? If not how can I get the beta?
Thanks,
Maher
nullHi Maher,
We hope to release this capability within the next few weeks.
I will mail you directly.
John
Maher (guest) wrote:
: Is the the workbench available? If not how can I get the beta?
: Thanks,
: Maher
Oracle Technology Network
http://technet.oracle.com
null -
Migration from SQL Server 2008 to Oracle 11g
Hi there,
I have a quick question, Anyone who have experienced to migration procedures,function from SQL Server 2008 to 11g R2. Is it possible? I migrated tables and views through Oracle heterogenious servinces but I am not sure about the fucntions and procedures.
Any help would be appreciated.
Warm regards,Automated conversions are possible. After these conversions the system will pretty much run. However, and it can be a pretty big HOWEVER, performance could well take a hit - which the uninitiated or SQL Server acolytes will seek to blame on Oracle not being very good. This is not actually the case.
You could be in for a major review and rewrite. Besides the syntax differences in the procedural languages, there is a huge - like really huge - difference in transaction control, isolation, and read consistency. Basically, keep in mind that Oracle reads do not block writes, writes do not block reads, and there are no dirty reads. Writes only block other writes. Thus, no coding 'tricks' are needed to get around these blockers. Oracle has global temporary tables that are generally used to help out those converting from SQL Server. In actuality, then are mostly not needed as you can almost always do your work in one SQL statement.
Read the concepts guide from cover to cover, then do it again, then start looking at what you need to do to convert your procedural code. -
Migration from SQL SERVER 7.0 to oracle 8i (8.1.7)
Does any one have experience in migrating SQL SERVER 7.0 database to Oracle 8.1.7?
Hi,
U can convert from sql server to Oracle 8 but u've to look after the stored procedures in mssql server. If the stored procedures contains any temporary table concepts and resultset then some manual changes are required.
Thanx,
Durai.
null -
Migration from SQL Server 7.0 to Oracle 8.0.5
Can we migrate from SQL Server 7.0 to Oracle 8.0.5 directly without being converted to Oracle 8i objects
Hi,
U can convert from sql server to Oracle 8 but u've to look after the stored procedures in mssql server. If the stored procedures contains any temporary table concepts and resultset then some manual changes are required.
Thanx,
Durai.
null -
Converting application SQL code
I see that the migration workbench will convert stored procedures. Are there any tools that will help to sniff out or convert application SQL code for MS SQL into SQL supported by Oracle. I am converting from SQL Server 7 to Oracle 8i. Any help would be appreciated
Hello,
Yes it probably will return multiple rows...but I spot this:
CURSOR c_schemas IS
select owner from <table>@<db-link> where table_name = 'DDL_LOG' and num_rows > 0 order by owner;
Does that cursor return multiple rows as well? Or just one? Because if it returns more rows you'll get multiple SQL statements...
Good links?? There is APEX documentation in your installation directory...
Just try the different kinds of regions I suggested, see if it works and what fits your needs the best.
Greetings,
Roel
http://roelhartman.blogspot.com/
http://www.bloggingaboutoracle.org/
http://www.logica.com/ -
Cannot convert from java.util.Date to java.sql.Date
In the below code am trying to get the current date and 60 days prior date:
Date todayDate;
Date Sixtydaysprior;
String DATE_FORMAT = "MM/dd/yy";
DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Calendar cal = Calendar.getInstance();
todayDate = sdf.parse(sdf.format(cal.getTime()));
cal.add(Calendar.DATE, -60);
Sixtydaysprior = sdf.parse(sdf.format(cal.getTime()));I have imported following files:
<%@page
import="java.util.Calendar,
java.text.SimpleDateFormat,
java.text.ParseException,
java.util.*"
%>Shows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
Thanks.
Edited by: MiltonDetroja on May 22, 2009 11:03 AMShows up following error msg:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
I don't think this exception is thrown from the portion of code you have shown. As clearly specified in exception message, you cannot cast an instance of java.util.Date to java.sql.Date. you will need to do something like this
java.util.Date today = new java.util.Date();
long t = today.getTime();
java.sql.Date dt = new java.sql.Date(t); -
Convert from NVARCHAR2 to Unicode in SQL Plus
I need to convert from NVARCHAR2 column data to Unicode format in a query. How can I do this?
I need to convert from NVARCHAR2 column data to Unicode format in a queryMaybe with convert:
SQL> select convert(n'ABC', 'utf8') abc from dual;
AB
┐
1 row selected.? -
Re: How to converting from PL/SQL query to T-SQL query
How to converting from PL/SQL query to T-SQL query... Its Urgent
Download the
SQL Server Migration Assistant for Oracle. It will convert whole Oracle databases, or single queries or PL/SQL stored procedures.
With caution that If your database is using Collation which is case sensitive SSMA will not work.SSMA doesnt guarantees 100% for conversion of Queries/stored proc /database if it fails to do so for some queries you will have to do it manually.
But you can try
Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers -
Convert BW from Sql Server to Oracle
Does anyone know of any documents that discuss converting an existing BW implementation from Sql Server to Oracle?
Never heard about ... we did something similar but creating a "new" BW sys by Change Requests, and the populating it with data.
Hope it helps
GFV -
How to delete the Folder from sql server 2008
Hi all,
I was trying to delete the folder from sql server 2008 with the below script
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @cmd VARCHAR(8000)
DECLARE @folderName VARCHAR(256) -- filename for backup
SET @folderName = + (CONVERT(varchar(10), GETDATE()-7, 112)) -- 7 days back date folder name
SET @path = 'I:\Backup_Test\' + @folderName -- Folder path
SET @cmd = 'del ' + @path -- Delete
EXEC master..xp_cmdshell @cmd
--Print @cmd
This is not working it was asking the Confirmation (I:\Backup_Test\20100629\*, Are you sure (Y/N)? ) what will i do to the delete the folder.
Thanks,
Prasad R.I would notice you that T-SQL does not play well to do things like that. Do not you want using .net language to delete folders?
Old method is
declare @HR int, @CFOLDER varchar(255),@FSO int
set @CFOLDER='D:\folder\'
EXEC @HR = sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
EXEC @HR = sp_OAMethod @FSO, null, 'DeleteFolder', @CFOLDER
Now regarding to your second question please examine xp_fileexist system stored procedure
CREATE FUNCTION dbo.fn_file_exists(@filename VARCHAR(300))
RETURNS INT
AS
BEGIN
DECLARE @file_exists AS INT
EXEC master..xp_fileexist @filename, @file_exists OUTPUT
RETURN @file_exists
END
GO
-- test
SELECT dbo.fn_file_exists('c:\a.txt')
Best Regards, Uri Dimant SQL Server MVP http://dimantdatabasesolutions.blogspot.com/ http://sqlblog.com/blogs/uri_dimant/
Maybe you are looking for
-
Safari Crashes when I try to send attachment
i use gmail. when i try to send an attachment safari crashes. i'm fed up! Process: Safari [892] Path: /Applications/Safari.app/Contents/MacOS/Safari Identifier: com.apple.Safari Version: 3.2.1 (5525.27.1) Build Info: WebBrowser-55252701~1 Code Type:
-
Cannot download drivers for my network adapter - Gigabyte X58A-UD5 Motherboard
Hey everyone, I recently got tired of my wireless connection for obvious reasons and decided to run an ethernet cable from my modem to my computer. I once I plugged in the ethernet cable nothing happened; I was confused and checked my network adapter
-
My computer is authorized yet one song wont play and says it needs authorization what do i do
i just bought a song and when I try to play it it says my computer needs to be authorized. When I hit authorize, it says my computer is already authorized yet thie song still wont play because it still says computer needs to be authorized. Whats wron
-
Number of entries in each table
Hi, I have a requirement to find the number of entries in each table in the system, how do I find this? If I have to goto each table & find out it is a tedious job. Do we have any standard report kind of thing to find out the number of entries in all
-
In the new iTunes 11, in the store, if I click on an album I see the "Name", "Artist", "Time", "Popularity" and "Price" columns. But no the "Composer" column, a useful information especially for classical music. There is a way to see the Composer col