Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Thursday, March 29, 2012

Converting empty string to Null when inserting/updating

I am using the following query to calculate date differences:
select ........DATEDIFF(d, recruitment_advertising.advertising_date, career_details.RTS_Email AS Datetime) AS Ad_to_RTS_days FROM ....

I have stored all my dates as NVARCHAR because of the issues with localization.
If the value is an empty String my output is eg: -38700. which is way off and incorrect. Some of the values in my table areNULL and they produce the correct result.

Is there a T-SQL statement to replace empy Strings with the NULL value in my tables.
I'd like to use it as a trigger when inserting or updating to convert empty strings to NULL
before the values are inserted.

Thanks guys.

You REALLY should store your dates as a datetime. There is no localization "Problem" with datetimes if you use them correctly, and you can't sort and/or generate good indexes if they are stored in a nvarchar field (Unless you specifically use the YYYYMMDD or YYYY-MM-DD format).

That aside, yes, try NULLIF() like:

INSERT INTO MyTable(col1) VALUES (NULLIF(@.val1,''))

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_nos-nz_3uhy.asp

Converting DateTime

Hi,
When I open a tabe in the SQL enterprise manager I see the Timestamp Field
in this Format :
24/01/2005 16:45:00

However when I'm using the Query analyzer or other SQL Client I see the
Timestamp Field in this Format :
2005-01-24 16:44:59.997

Does Anybody know what to do in order to display the Timestamp Field in
first Format (24/01/2005 16:45:00) ?

Please Advise,
Yariv

--
Message posted via http://www.sqlmonster.comLook up "Date Time String Transformation" in SQL Server BOL

"Yariv via SQLMonster.com" <forum@.SQLMonster.com> wrote in message
news:732a9f6af71c48d6ab1ff539f0fe3351@.SQLMonster.c om...
> Hi,
> When I open a tabe in the SQL enterprise manager I see the Timestamp Field
> in this Format :
> 24/01/2005 16:45:00
> However when I'm using the Query analyzer or other SQL Client I see the
> Timestamp Field in this Format :
> 2005-01-24 16:44:59.997
> Does Anybody know what to do in order to display the Timestamp Field in
> first Format (24/01/2005 16:45:00) ?
> Please Advise,
> Yariv
> --
> Message posted via http://www.sqlmonster.com|||"Yariv via SQLMonster.com" <forum@.SQLMonster.com> wrote in message
news:732a9f6af71c48d6ab1ff539f0fe3351@.SQLMonster.c om...
> Hi,
> When I open a tabe in the SQL enterprise manager I see the Timestamp Field
> in this Format :
> 24/01/2005 16:45:00
> However when I'm using the Query analyzer or other SQL Client I see the
> Timestamp Field in this Format :
> 2005-01-24 16:44:59.997
> Does Anybody know what to do in order to display the Timestamp Field in
> first Format (24/01/2005 16:45:00) ?
> Please Advise,
> Yariv
> --
> Message posted via http://www.sqlmonster.com

Check out CONVERT() in Books Online. But you need to remember that MSSQL
stores datetime values in an internal format, and each client (including EM
and QA) decides how to display them. See here for more details:

http://www.karaszi.com/sqlserver/info_datetime.asp

Simon|||Yariv via SQLMonster.com (forum@.SQLMonster.com) writes:
> When I open a tabe in the SQL enterprise manager I see the Timestamp Field
> in this Format :
> 24/01/2005 16:45:00
> However when I'm using the Query analyzer or other SQL Client I see the
> Timestamp Field in this Format :
> 2005-01-24 16:44:59.997
> Does Anybody know what to do in order to display the Timestamp Field in
> first Format (24/01/2005 16:45:00) ?

Under Tool->Options->Connections, check the third checkbox, "Use
regional settings...".

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

converting date format on for xml query

im trying to convert date format with this with no sucess
http://myserver/?sql=select%20*%20,CONVERT(datetime,DATA,3)
as%20[order!1!date]%20FROM%20NOTIFURBANA%20FOR%20XML%
20AUTO&root=root
it order by date, but dont convert the date format...any
help ?
What is the date formay you want to get? Note that all datetime values will
mapped to an ISO format. If you want your own format, CONVERT to a string in
your select statement.
Michael
"max" <anonymous@.discussions.microsoft.com> wrote in message
news:7df801c43160$6ca153b0$a001280a@.phx.gbl...
> im trying to convert date format with this with no sucess
> http://myserver/?sql=select%20*%20,CONVERT(datetime,DATA,3)
> as%20[order!1!date]%20FROM%20NOTIFURBANA%20FOR%20XML%
> 20AUTO&root=root
> it order by date, but dont convert the date format...any
> help ?
|||hi
thanks
im trying to get the datetime field that on my sql is on
this format
3/5/2004 14:30:18
but on xml it shows me this
2004-05-03T14:30:18
and i want it to return me
DD/MM/YY HH:MM:SS
how could it be done
max

>--Original Message--
>What is the date formay you want to get? Note that all
datetime values will
>mapped to an ISO format. If you want your own format,
CONVERT to a string in
>your select statement.
>Michael
>"max" <anonymous@.discussions.microsoft.com> wrote in
message[vbcol=seagreen]
>news:7df801c43160$6ca153b0$a001280a@.phx.gbl...
sucess[vbcol=seagreen]
(datetime,DATA,3)
>
>.
>
|||its impossible or something ?
thanks
max
[vbcol=seagreen]
>--Original Message--
>hi
>thanks
>im trying to get the datetime field that on my sql is on
>this format
>3/5/2004 14:30:18
>but on xml it shows me this
>2004-05-03T14:30:18
>and i want it to return me
>DD/MM/YY HH:MM:SS
>how could it be done
>
>max
>
>datetime values will
>CONVERT to a string in
>message
>sucess
>(datetime,DATA,3)
format...any
>.
>
|||Here you are:
create table t (d datetime)
go
insert into t values ('3/5/2004 14:30:18')
go
select CONVERT(nvarchar(50), d, 101)+' '+CONVERT(nvarchar(50), d, 108) as d
from t for xml auto
HTH
Michael
<anonymous@.discussions.microsoft.com> wrote in message
news:7ada01c43164$b6cf3520$a401280a@.phx.gbl...[vbcol=seagreen]
> hi
> thanks
> im trying to get the datetime field that on my sql is on
> this format
> 3/5/2004 14:30:18
> but on xml it shows me this
> 2004-05-03T14:30:18
> and i want it to return me
> DD/MM/YY HH:MM:SS
> how could it be done
>
> max
>
> datetime values will
> CONVERT to a string in
> message
> sucess
> (datetime,DATA,3)
sqlsql

Converting Date

I am unable to convert following date format in seconds (ss). Plz provide me query for the same.
Date Available :
2007-03-27 09:55:00.000select convert(datetime, '2007-03-27 09:55:00.000')

??|||select convert(datetime, '2007-03-27 09:55:00.000')
Yes, and the seconds are extracted by:
select datepart(ss, convert(datetime, '2007-03-27 09:55:00.000'))|||even the convet part of

select datepart(ss, convert(datetime, '2007-03-27 09:55:00.000'))

can be avoided and used as

select datepart(ss,'2007-03-27 09:55:00.000')|||but select datepart(ss,'2007-03-27 09:55:00.000') yields 0

i think perhaps milind wanted the answer to be 3383974800, which is that datetime converted in seconds in SQL Server

note that in unix timestamp format, the value would be 1175003700|||Perhaps, yes. Then the query he asked would be:

SELECT 3383974800|||no, not really, because you don't get that answer without doing a conversion

for example, what is the answer for '2006-09-09 09:37'?|||'2006-09-09 09:37' is not one of the available dates listed in the OP. ;)

Seriously, I think we need Milind to clarify what s/he wants.|||'2006-09-09 09:37' is not one of the available dates listed in the OP. ;)

good one :cool:

Tuesday, March 27, 2012

Converting data

Hi all,
I have the following questions :
1)
I have a query :
SELECT staffl.prijslijst AS pricelist, staffl.ARTCODE AS PhantomItem,
(CASE items.class_01 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
items.class_01 AND itemclasses.CLASSid = 1) END) AS class_01,
staffl.bedr1,
(CASE items.class_10 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
items.class_10 AND itemclasses.CLASSid = 10) END)
AS class_10 FROM staffl INNER JOIN stfoms ON stfoms.prijslijst =
staffl.prijslijst INNER JOIN items ON items.itemcode = staffl.artcode
AND items.type = 'P' AND stfoms.type = 'S' AND stfoms.main_pricelist <> 1
AND SUBSTRING(staffl.ARTCODE, 1, LEN(staffl.prijslijst)) = staffl.prijslijst
AND items.IsSalesItem = 0
ORDER BY staffl.pricelist
Which give me next output :
Pricelist class_01 bedr1
0000 Item1 0
0000 Item2 15
0000 Item15 10
All "CLASS_01" items go to 15 for each pricelist.
I like to convert this within SQL with Query or DTS to next structure,
so Pricelist and Bedr1 in 1 row with CLASS01 in columns (15 total) :
Pricelist item1 item2 item15
0000 0 15 10
2)
Other query is :
SELECT cicmpy.debnr, cicmpy.PriceList FROM cicmpy LEFT OUTER JOIN cicntp ON
cicmpy.cnt_id = cicntp.cnt_id WHERE debcode IS NOT NULL
ORDER BY cicmpy.debcode
Output is :
debnr pricelist
1 2025
2 SALESPRICE
3 3001
What I need is to combine both queries to get 1 output as following,
so merge the 2 queries to 1 to get 1 combined output, with 1 special thing :
Where SALESPRICE = pricelist '0000' :
Deb Pricelist item1 item2 item15
1 2025 0 25 10
2 0000 0 10 10
1 3001 0 32 10
Can anybody help me ?
This is crosstab query
SELECT Pricelist ,MAX(CASE WHEN class_01 ='Item1' THEN bedr1 END)
'Item1,
..................... Do that for all items here
FROM Table
GROUP BY Pricelist
"Jeroen" <Jeroen@.discussions.microsoft.com> wrote in message
news:D64B9FBA-A315-4B5A-B088-2964054C3B3E@.microsoft.com...
> Hi all,
> I have the following questions :
> 1)
> I have a query :
> SELECT staffl.prijslijst AS pricelist, staffl.ARTCODE AS PhantomItem,
> (CASE items.class_01 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
> items.class_01 AND itemclasses.CLASSid = 1) END) AS class_01,
> staffl.bedr1,
> (CASE items.class_10 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
> items.class_10 AND itemclasses.CLASSid = 10) END)
> AS class_10 FROM staffl INNER JOIN stfoms ON stfoms.prijslijst =
> staffl.prijslijst INNER JOIN items ON items.itemcode = staffl.artcode
> AND items.type = 'P' AND stfoms.type = 'S' AND stfoms.main_pricelist <> 1
> AND SUBSTRING(staffl.ARTCODE, 1, LEN(staffl.prijslijst)) =
> staffl.prijslijst
> AND items.IsSalesItem = 0
> ORDER BY staffl.pricelist
> Which give me next output :
> Pricelist class_01 bedr1
> 0000 Item1 0
> 0000 Item2 15
> 0000 Item15 10
> All "CLASS_01" items go to 15 for each pricelist.
> I like to convert this within SQL with Query or DTS to next structure,
> so Pricelist and Bedr1 in 1 row with CLASS01 in columns (15 total) :
> Pricelist item1 item2 item15
> 0000 0 15 10
> 2)
> Other query is :
> SELECT cicmpy.debnr, cicmpy.PriceList FROM cicmpy LEFT OUTER JOIN cicntp
> ON
> cicmpy.cnt_id = cicntp.cnt_id WHERE debcode IS NOT NULL
> ORDER BY cicmpy.debcode
> Output is :
> debnr pricelist
> 1 2025
> 2 SALESPRICE
> 3 3001
> What I need is to combine both queries to get 1 output as following,
> so merge the 2 queries to 1 to get 1 combined output, with 1 special thing
> :
> Where SALESPRICE = pricelist '0000' :
> Deb Pricelist item1 item2 item15
> 1 2025 0 25 10
> 2 0000 0 10 10
> 1 3001 0 32 10
> Can anybody help me ?
>
|||Hi Uri,
not very into SQL (newbie).
I am not sure how to use this in my current query....
"Uri Dimant" wrote:

> This is crosstab query
> SELECT Pricelist ,MAX(CASE WHEN class_01 ='Item1' THEN bedr1 END)
> 'Item1,
> ..................... Do that for all items here
> FROM Table
> GROUP BY Pricelist
>
> "Jeroen" <Jeroen@.discussions.microsoft.com> wrote in message
> news:D64B9FBA-A315-4B5A-B088-2964054C3B3E@.microsoft.com...
>
>

Converting data

Hi all,
I have the following questions :
1)
I have a query :
SELECT staffl.prijslijst AS pricelist, staffl.ARTCODE AS PhantomItem,
(CASE items.class_01 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
items.class_01 AND itemclasses.CLASSid = 1) END) AS class_01,
staffl.bedr1,
(CASE items.class_10 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
items.class_10 AND itemclasses.CLASSid = 10) END)
AS class_10 FROM staffl INNER JOIN stfoms ON stfoms.prijslijst =
staffl.prijslijst INNER JOIN items ON items.itemcode = staffl.artcode
AND items.type = 'P' AND stfoms.type = 'S' AND stfoms.main_pricelist <> 1
AND SUBSTRING(staffl.ARTCODE, 1, LEN(staffl.prijslijst)) = staffl.prijslijst
AND items.IsSalesItem = 0
ORDER BY staffl.pricelist
Which give me next output :
Pricelist class_01 bedr1
0000 Item1 0
0000 Item2 15
0000 Item15 10
All "CLASS_01" items go to 15 for each pricelist.
I like to convert this within SQL with Query or DTS to next structure,
so Pricelist and Bedr1 in 1 row with CLASS01 in columns (15 total) :
Pricelist item1 item2 item15
0000 0 15 10
2)
Other query is :
SELECT cicmpy.debnr, cicmpy.PriceList FROM cicmpy LEFT OUTER JOIN cicntp ON
cicmpy.cnt_id = cicntp.cnt_id WHERE debcode IS NOT NULL
ORDER BY cicmpy.debcode
Output is :
debnr pricelist
1 2025
2 SALESPRICE
3 3001
What I need is to combine both queries to get 1 output as following,
so merge the 2 queries to 1 to get 1 combined output, with 1 special thing :
Where SALESPRICE = pricelist '0000' :
Deb Pricelist item1 item2 item15
1 2025 0 25 10
2 0000 0 10 10
1 3001 0 32 10
Can anybody help me ?This is crosstab query
SELECT Pricelist ,MAX(CASE WHEN class_01 ='Item1' THEN bedr1 END)
'Item1,
..................... Do that for all items here
FROM Table
GROUP BY Pricelist
"Jeroen" <Jeroen@.discussions.microsoft.com> wrote in message
news:D64B9FBA-A315-4B5A-B088-2964054C3B3E@.microsoft.com...
> Hi all,
> I have the following questions :
> 1)
> I have a query :
> SELECT staffl.prijslijst AS pricelist, staffl.ARTCODE AS PhantomItem,
> (CASE items.class_01 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
> items.class_01 AND itemclasses.CLASSid = 1) END) AS class_01,
> staffl.bedr1,
> (CASE items.class_10 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode =
> items.class_10 AND itemclasses.CLASSid = 10) END)
> AS class_10 FROM staffl INNER JOIN stfoms ON stfoms.prijslijst =
> staffl.prijslijst INNER JOIN items ON items.itemcode = staffl.artcode
> AND items.type = 'P' AND stfoms.type = 'S' AND stfoms.main_pricelist <> 1
> AND SUBSTRING(staffl.ARTCODE, 1, LEN(staffl.prijslijst)) =
> staffl.prijslijst
> AND items.IsSalesItem = 0
> ORDER BY staffl.pricelist
> Which give me next output :
> Pricelist class_01 bedr1
> 0000 Item1 0
> 0000 Item2 15
> 0000 Item15 10
> All "CLASS_01" items go to 15 for each pricelist.
> I like to convert this within SQL with Query or DTS to next structure,
> so Pricelist and Bedr1 in 1 row with CLASS01 in columns (15 total) :
> Pricelist item1 item2 item15
> 0000 0 15 10
> 2)
> Other query is :
> SELECT cicmpy.debnr, cicmpy.PriceList FROM cicmpy LEFT OUTER JOIN cicntp
> ON
> cicmpy.cnt_id = cicntp.cnt_id WHERE debcode IS NOT NULL
> ORDER BY cicmpy.debcode
> Output is :
> debnr pricelist
> 1 2025
> 2 SALESPRICE
> 3 3001
> What I need is to combine both queries to get 1 output as following,
> so merge the 2 queries to 1 to get 1 combined output, with 1 special thing
> :
> Where SALESPRICE = pricelist '0000' :
> Deb Pricelist item1 item2 item15
> 1 2025 0 25 10
> 2 0000 0 10 10
> 1 3001 0 32 10
> Can anybody help me ?
>|||Hi Uri,
not very into SQL (newbie).
I am not sure how to use this in my current query....
"Uri Dimant" wrote:

> This is crosstab query
> SELECT Pricelist ,MAX(CASE WHEN class_01 ='Item1' THEN bedr1 END)
> 'Item1,
> ..................... Do that for all items here
> FROM Table
> GROUP BY Pricelist
>
> "Jeroen" <Jeroen@.discussions.microsoft.com> wrote in message
> news:D64B9FBA-A315-4B5A-B088-2964054C3B3E@.microsoft.com...
>
>

Converting data

Hi all,
I have the following questions :
1)
I have a query :
SELECT staffl.prijslijst AS pricelist, staffl.ARTCODE AS PhantomItem,
(CASE items.class_01 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode = items.class_01 AND itemclasses.CLASSid = 1) END) AS class_01,
staffl.bedr1,
(CASE items.class_10 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode = items.class_10 AND itemclasses.CLASSid = 10) END)
AS class_10 FROM staffl INNER JOIN stfoms ON stfoms.prijslijst = staffl.prijslijst INNER JOIN items ON items.itemcode = staffl.artcode
AND items.type = 'P' AND stfoms.type = 'S' AND stfoms.main_pricelist <> 1
AND SUBSTRING(staffl.ARTCODE, 1, LEN(staffl.prijslijst)) = staffl.prijslijst
AND items.IsSalesItem = 0
ORDER BY staffl.pricelist
Which give me next output :
Pricelist class_01 bedr1
0000 Item1 0
0000 Item2 15
0000 Item15 10
All "CLASS_01" items go to 15 for each pricelist.
I like to convert this within SQL with Query or DTS to next structure,
so Pricelist and Bedr1 in 1 row with CLASS01 in columns (15 total) :
Pricelist item1 item2 item15
0000 0 15 10
2)
Other query is :
SELECT cicmpy.debnr, cicmpy.PriceList FROM cicmpy LEFT OUTER JOIN cicntp ON
cicmpy.cnt_id = cicntp.cnt_id WHERE debcode IS NOT NULL
ORDER BY cicmpy.debcode
Output is :
debnr pricelist
1 2025
2 SALESPRICE
3 3001
What I need is to combine both queries to get 1 output as following,
so merge the 2 queries to 1 to get 1 combined output, with 1 special thing :
Where SALESPRICE = pricelist '0000' :
Deb Pricelist item1 item2 item15
1 2025 0 25 10
2 0000 0 10 10
1 3001 0 32 10
Can anybody help me ?This is crosstab query
SELECT Pricelist ,MAX(CASE WHEN class_01 ='Item1' THEN bedr1 END)
'Item1,
..................... Do that for all items here
FROM Table
GROUP BY Pricelist
"Jeroen" <Jeroen@.discussions.microsoft.com> wrote in message
news:D64B9FBA-A315-4B5A-B088-2964054C3B3E@.microsoft.com...
> Hi all,
> I have the following questions :
> 1)
> I have a query :
> SELECT staffl.prijslijst AS pricelist, staffl.ARTCODE AS PhantomItem,
> (CASE items.class_01 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode => items.class_01 AND itemclasses.CLASSid = 1) END) AS class_01,
> staffl.bedr1,
> (CASE items.class_10 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode => items.class_10 AND itemclasses.CLASSid = 10) END)
> AS class_10 FROM staffl INNER JOIN stfoms ON stfoms.prijslijst => staffl.prijslijst INNER JOIN items ON items.itemcode = staffl.artcode
> AND items.type = 'P' AND stfoms.type = 'S' AND stfoms.main_pricelist <> 1
> AND SUBSTRING(staffl.ARTCODE, 1, LEN(staffl.prijslijst)) => staffl.prijslijst
> AND items.IsSalesItem = 0
> ORDER BY staffl.pricelist
> Which give me next output :
> Pricelist class_01 bedr1
> 0000 Item1 0
> 0000 Item2 15
> 0000 Item15 10
> All "CLASS_01" items go to 15 for each pricelist.
> I like to convert this within SQL with Query or DTS to next structure,
> so Pricelist and Bedr1 in 1 row with CLASS01 in columns (15 total) :
> Pricelist item1 item2 item15
> 0000 0 15 10
> 2)
> Other query is :
> SELECT cicmpy.debnr, cicmpy.PriceList FROM cicmpy LEFT OUTER JOIN cicntp
> ON
> cicmpy.cnt_id = cicntp.cnt_id WHERE debcode IS NOT NULL
> ORDER BY cicmpy.debcode
> Output is :
> debnr pricelist
> 1 2025
> 2 SALESPRICE
> 3 3001
> What I need is to combine both queries to get 1 output as following,
> so merge the 2 queries to 1 to get 1 combined output, with 1 special thing
> :
> Where SALESPRICE = pricelist '0000' :
> Deb Pricelist item1 item2 item15
> 1 2025 0 25 10
> 2 0000 0 10 10
> 1 3001 0 32 10
> Can anybody help me ?
>|||Hi Uri,
not very into SQL (newbie).
I am not sure how to use this in my current query....
"Uri Dimant" wrote:
> This is crosstab query
> SELECT Pricelist ,MAX(CASE WHEN class_01 ='Item1' THEN bedr1 END)
> 'Item1,
> ..................... Do that for all items here
> FROM Table
> GROUP BY Pricelist
>
> "Jeroen" <Jeroen@.discussions.microsoft.com> wrote in message
> news:D64B9FBA-A315-4B5A-B088-2964054C3B3E@.microsoft.com...
> > Hi all,
> >
> > I have the following questions :
> >
> > 1)
> > I have a query :
> >
> > SELECT staffl.prijslijst AS pricelist, staffl.ARTCODE AS PhantomItem,
> > (CASE items.class_01 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> > itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode => > items.class_01 AND itemclasses.CLASSid = 1) END) AS class_01,
> > staffl.bedr1,
> > (CASE items.class_10 WHEN 'ALL' THEN 'ALL' ELSE (SELECT
> > itemclasses.description FROM itemclasses WHERE itemclasses.itemClassCode => > items.class_10 AND itemclasses.CLASSid = 10) END)
> >
> > AS class_10 FROM staffl INNER JOIN stfoms ON stfoms.prijslijst => > staffl.prijslijst INNER JOIN items ON items.itemcode = staffl.artcode
> > AND items.type = 'P' AND stfoms.type = 'S' AND stfoms.main_pricelist <> 1
> > AND SUBSTRING(staffl.ARTCODE, 1, LEN(staffl.prijslijst)) => > staffl.prijslijst
> > AND items.IsSalesItem = 0
> > ORDER BY staffl.pricelist
> >
> > Which give me next output :
> >
> > Pricelist class_01 bedr1
> > 0000 Item1 0
> > 0000 Item2 15
> > 0000 Item15 10
> >
> > All "CLASS_01" items go to 15 for each pricelist.
> >
> > I like to convert this within SQL with Query or DTS to next structure,
> > so Pricelist and Bedr1 in 1 row with CLASS01 in columns (15 total) :
> >
> > Pricelist item1 item2 item15
> > 0000 0 15 10
> >
> > 2)
> > Other query is :
> >
> > SELECT cicmpy.debnr, cicmpy.PriceList FROM cicmpy LEFT OUTER JOIN cicntp
> > ON
> > cicmpy.cnt_id = cicntp.cnt_id WHERE debcode IS NOT NULL
> >
> > ORDER BY cicmpy.debcode
> >
> > Output is :
> >
> > debnr pricelist
> > 1 2025
> > 2 SALESPRICE
> > 3 3001
> >
> > What I need is to combine both queries to get 1 output as following,
> > so merge the 2 queries to 1 to get 1 combined output, with 1 special thing
> > :
> > Where SALESPRICE = pricelist '0000' :
> >
> > Deb Pricelist item1 item2 item15
> > 1 2025 0 25 10
> > 2 0000 0 10 10
> > 1 3001 0 32 10
> >
> > Can anybody help me ?
> >
> >
>
>

converting columns in an INSERT (was "SQL Query")

I'm trying to create an Insert query and I'm having difficulty in 2 areas:

First, I would like to CAST/CONVERT a single column of the several columns in the tables below. Is it possible to retain the asterisk identifying all columns and single out a particular column to be converted as opposed to writing out each individual column in both the INSERT and SELECT statements? I would like to CONVERT the column "MILL_COST" from VARCHAR(50) to Money.

INSERT INTO ITEM_MASTER
SELECT *
FROM ITEM_MASTER_TEMP

Second, I've tried the following"conversions" in the SELECT statement, to no avail:

CONVERT(Money, MILL_COST) As MILL_COST
CONVERT(Money, CONVERT(Varchar(50), MILL_COST)
CAST(MILL_COST AS Money)

Any pointers much appreciated...First of all, I'd strongly suggest that you list out the columns. That solves all kinds of problems before they get a chance to happen to you. If you are determined to do things the hard way, you don't have to enumerate the columns yourself, but I'd still recommend it.

You ought to be able to use any of those conversions if you like, but as long as the contents of the column can be converted to MONEY, the SQL Server engine ought to handle the conversion for you.

-PatP|||"SELECT *" is shorthand for "I'm a lazy programmer". I would never leave it in any finished code. Bad. Bad. Bad bad code.

Converting column values

I have a column that is frequently updated with an append query. I need to turn all of the incoming positive values into negative values (as well as convert all of the existing). I tried to multiply the column by -1 in the formula option in table design view but couldn't find the proper formula format.

Can anyone suggest an approach.I'd use something like:UPDATE myTable
SET bogusColumn = - Abs(bogusColumn)-PatP

Sunday, March 25, 2012

Converting binary to string

is there a way to query a varbinary column and print the readable char in query analyzer?

thanks in advance!

Ryan

No way to do this, because SQL only store the binary data and has no sense for character encoding and structure of the doc.|||

There is a way, here it is...

declare @.pass varchar(30)
declare @.binPass varbinary(8)
set @.binPass = (select password from tblEMP where empid = '123')
set @.pass = (select cast(@.binPass as varchar(20)))
print reverse(@.pass)

I get characters like squares after the text, but I know to disregard them and only look at the text. Anyone know how to get rid of the squares and weird characters? thanks

Ryan

|||

SQL Server will convert varbinary to varchar what it will not convert is varbinary to text. Try the link below for the complete conversion chart and code samples. Hope this helps.

http://msdn2.microsoft.com/en-us/library/ms187928.aspx

sqlsql

converting access to sqlserver 7

I have a query which fixes area codes. it runs:
UPDATE (nocall INNER JOIN pildta ON (nocall.SUFF = pildta.suff) AND (nocall.PREF = pildta.preff) AND (nocall.AREA = pildta.area)) INNER JOIN ZipCodeUS ON pildta.Zip = ZipCodeUS.ZIP SET nocall.AREA = [a/c]
WHERE (((IIf([nocall]![area]<>[a/c],1,0))=1));

I managed to replace the IIF with a CASE for displaying the unmatched tables like this:
SELECT dbo.nocall.AREA, dbo.pildta.Zip, dbo.ZipCodeUS.[A/C], case when [a/c]=[nocall].[area] then 1 else 0 end as match
FROM dbo.pildta INNER JOIN
dbo.ZipCodeUS ON dbo.pildta.Zip = dbo.ZipCodeUS.ZIP INNER JOIN
dbo.nocall ON dbo.pildta.area = dbo.nocall.AREA AND dbo.pildta.preff = dbo.nocall.PREF AND dbo.pildta.suff = dbo.nocall.SUFF

How can I make this an update query based on [match] having a value of 1?How about moving the [a/c]=[nocall].[area] from a CASE clause to a WHERE clause (which should limit the results to records that would return a 1 in your CASE clause), and then making that query a subquery to your UPDATE command? E.g., UPDATE table SET column = value WHERE tableprimarykey IN (subquery).|||ok. What am I doing wrong. I'm now trying this:
UPDATE nocall
SET AREA = [a/c] IN (SELECT ZipCodeUS.[A/C] FROM ZipCodeUS INNER JOIN pildta ON ZipCodeUS.ZIP = pildta.Zip INNER JOIN nocall ON pildta.area = nocall.AREA AND pildta.preff = nocall.PREF AND pildta.suff = nocall.SUFF)
WHERE [ctr]=[ctr] IN (SELECT nocall.AREA, ZipCodeUS.[A/C], nocall.ctr FROM ZipCodeUS INNER JOIN pildta ON ZipCodeUS.ZIP = pildta.Zip INNER JOIN nocall ON pildta.area = nocall.AREA AND pildta.preff = nocall.PREF AND pildta.suff = nocall.SUFF AND ZipCodeUS.[A/C] <> nocall.AREA)

When i try to save, I get incorrect syntax near the keyword IN, incorrect syntax near the word WHERE|||Well, the first error in the query in your last post is "SET AREA = [a/c] IN (..." This would have to be like "SET AREA = [a/c] WHERE AREA IN (..."

I'm not sure I understand what the query is to accomplish well enough to give you complete rewrite, so tell me if this is correct:

Your goal is to replace values in NoCall.Area with values from ZipCodeUS.[A/C] when and only when:

1. NoCall.Area does not already equal ZipCodeUS.[A/C]
AND
2. ZipCodeUS has a matching record in Pildta based on .Zip
AND
3. NoCall has a record that matches Pildta's Area, Preff, and Suff

Converting Access Query to SQL Server Query

Would anyone know how to convert this Access Query to SQL Server Query?

Format((([ResponsivenessQ1]+[ResponsivenessQ2]+[ResponsivenessQ3]+[ResponsivenessQ4])/(IIf([ResponsivenessQ1]>0,1,0)+IIf([ResponsivenessQ2]>0,1,0)+IIf([ResponsivenessQ3]>0,1,0)+IIf([ResponsivenessQ4]>0,1,0))),"Standard")

What this query is doing in Access is Averaging numbers that are not equal to 0. If the number is equal to 0, it should not be averaged in. The average is set to 2 decimal places.try this

----optional just for testing --------
declare @.resq1 int,@.resq2 int,@.resq3 int,@.resq4 int
set @.resq1 = -1
set @.resq2 = 2
set @.resq3 = 0
set @.resq4 = 5
------end optional-----------

select convert(decimal(10,2),(@.resq1+@.resq2+@.resq3+@.resq4 )/((case when @.resq1 > 0 then 1 else 0 end)+
(case when @.resq2 > 0 then 1 else 0 end)+
(case when @.resq3 > 0 then 1 else 0 end)+
(case when @.resq4 > 0 then 1 else 0 end)))

Converting Access cross-tab query to SQL Server

I have an Access cross-tab query that conditionally breaks up a field into multiple groups and averages the results in each group and I am having trouble doing this in SQL Server. The SQL Server query I have below works but does not find the averages by node A, B, RA, or RB.

Is there a better way to do this than what I have below?

How would I do this in SQL Server?

In the Access query I use:

right( [Serial No], iif( len([Serial No])-3>=0, len([Serial No])-3, len([Serial No]))

Table:

[Work Order No] [Serial No] [Parameter Name] [Type] [Min] [Max] [Value] [Pass/Fail]

M1000 001A "Test Name" "System1" 0 100 50 P

M1000 001B "Test Name" "System1" 0 100 40 P

M1000 002A "Test Name" "System1" 0 100 45 P

M1000 002B "Test Name" "System1" 0 100 70 P

M1000 002RA "Test Name" "System1" 0 100 30 P

M1000 002RB "Test Name" "System1" 0 100 20 P

M1001 001A "Test Name" "System1" 0 100 50 P

M1001 001B "Test Name" "System1" 0 100 30 P

The Query Output should be:

[Work Order No] [Node] [Min] [Max] [Avg Value]

M1000 A 0 100 47.5

M1000 B 0 100 55

M1000 RA 0 100 30

M1000 RB 0 100 20

M1001 A 0 100 50

M1001 B 0 100 30

Access Query:

TRANSFORM Avg([Value]) AS AvgOfValue

SELECT [Work Order No], [Min], [Max], RIGHT( [Serial No], iif(len([Serial No])-3>=0,

len([Serial No])-3, len([Serial No]))) AS [Node], max([DateTime]) as [MaxOfDateTime]

FROM [Inspection Header] INNER JOIN [Inspection Data]

ON [Inspection Header].[Work Order No] = [Inspection Data].[Work Order No]

AND [Inspection Header].[Serial No] = [Inspection Data].[Serial No]

WHERE [Parameter Name] = "Test Name" AND [Pass/Fail] = "P"

GROUP BY [Work Order No], [Min], [Max], RIGHT([Serial No],iif(len([Serial No])-3>=0,

len([Serial No])-3, len([Serial No]))), [Pass/Fail]

PIVOT [Parameter Name]

Incomplete SQL Server Query:

set ANSI_NULLS OFF

set QUOTED_IDENTIFIER OFF

GO

ALTER procedure [dbo].[dt_AvgTest]

as

begin

select b.[Work Order No], b.[TN], c.[PF], d.[Min], d.[Max]

from (((select a.[Work Order No]

, avg(case a.[Parameter Name] when "Test Name" then [Value] end) as [TN]

from dbo.[Inspection Data] as a group by a.[Work Order No]) b

inner join (select [Work Order No], min([Pass/Fail]) as PF

from dbo.[Inspection Data] group by [Work Order No] ) c on c.[Work Order No] = b.[Work Order No] )

inner join (select [Work Order No], [Min], [Max]

from dbo.[Inspection Data] where [Parameter Name] = "Test Name" group by [Work Order No], [Min], [Max] ) d

on d.[Work Order No] = c.[Work Order No] )

where c.[PF] = 'P'

end

Sam:

Is your server running SQL Server 2000 or SQL Server 2005?


Dave

|||SQL Server 2005|||

-- -
-- 1. I am guessing based on the proposed output data that
-- the "Serial No" field must be broken apart to get the
-- [Node data]. This is a poor choice for data design.
-- This means that this field is not "atomic" and if
-- possible should be divided into two separate columns.
-- 2. I am assuming here that the "Parameter Name" column
-- contains quote characters as part of the target data.
-- 3. I am assuming here that the "Type" column contains
-- quote characters as part of the target data.
-- 4. I have chosen to display the "average value" field as
-- a numeric (9,1) column. It is unclear what the
-- precision of this field needs to be based on the
-- proposed output; it is likely that this display
-- column needs adjustment.
-- 5. The use of the 10-Level REPLACE function to remove
-- the numeric portion of the "Serial No" field to
-- obtain the "Node" portion of this field is a guess
-- that the "numeric" portion of the field is NOT a part
-- of the "Node". If this guess is not correct then
-- an alternate method of obtaining this field is
-- necessary.
-- 6. The "Min" and "Max" field are aggregated as a
-- precaution in case these fields should ever be
-- different for different line items. If these are
-- not aggregated an additional line will be generated
-- whenever these items might otherwise differ.
--
-- Questions:
-- 1. Can the "Serial No" field be broken down into
-- two separate fields?
-- 2. What are the rules for obtaining the "Node" data?
-- 3. What is the output specification for the "Value"
-- field.
-- -


select [Work Order No],
left (replace(replace(replace(replace(replace(replace(replace
(replace(replace(replace
([Serial No],'0',''),'1',''),'2',''),'3',''),'4',''),
'5',''),'6',''),'7',''),'8',''),'9',''), 10) as [Node],
min ([Min]) as [Min],
max ([Max]) as [Max],
convert (numeric (9,1), avg (convert (numeric (9,1), [value])))
as [Value]
from [Inspection Data]
where [Pass/Fail] = 'P'
and [Parameter Name] = '"Test Name"'
group by [Work Order No],
left (replace(replace(replace(replace(replace(replace(replace
(replace(replace(replace
([Serial No],'0',''),'1',''),'2',''),'3',''),'4',''),
'5',''),'6',''),'7',''),'8',''),'9',''), 10)
order by [Work Order No],
left (replace(replace(replace(replace(replace(replace(replace
(replace(replace(replace
([Serial No],'0',''),'1',''),'2',''),'3',''),'4',''),
'5',''),'6',''),'7',''),'8',''),'9',''), 10)


-- -- Sample Output

-- Work Order No Node Min Max Value
-- - -- -
-- M1000 A 0 100 47.5
-- M1000 B 0 100 55.0
-- M1000 RA 0 100 30.0
-- M1000 RB 0 100 20.0
-- M1001 A 0 100 50.0
-- M1001 B 0 100 30.0

|||

This worked great!

You are right about breaking the Serial Number down into two separate fields.

Thank you very much.

Sam

Converting Access Code - FORMAT

Hello,
A colleague passed me this make-table query which works in Access, and we'd
like to automate in SQL. I did some basic debugging but now on parse, SQL
returns that Trim and Format are not recognized function nameS. I think you
can see the what formatting is doing to provide a standard string length.
Could someone advise what I need to do to get this to work in SQL? Any help
would be much appreciated. Thanks, Pancho
SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
GVMOI2.TaxIDType,
GVMOI2.ApplicationCode, GVMOI2.AccountNo,
Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) &
Trim(GVMOI2.TraceNbr) AS TraceNbrEdt, IIf(IsNumeric(GVMOI2.CreditAmtCash),
Left(Format([CreditAmtCash],"0000000000.00"),10) &
Right(Format([CreditAmtCash],"0000000000.00"),2),
"000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2!DebitAmtCash),
Left(Format([DebitAmtCash],"0000000000.00"),10) &
Right(Format([DebitAmtCash],"0000000000.00"),2),
"000000000000") AS DebitAmtCashFmt,
IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10) &
Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
CreditAmtChecksFmt,
IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10) &
Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
DebitAmtChecksFmt,
GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
GVMOI2.CheckReferenceNbr,
GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
GVMOI2.ThirdParty,
"0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
GVMOI2.IDNumber,
GVMOI2.IDIssueBy, GVMOI2.IDOthers
INTO MOI_Prep
FROM GVMOI2;Follow the below guidelines to convert the query.
1. & ==> +
2. iif(<condition>,<true>,<false> ) ==> case when <condition> then <true>
else <false> end
3. <table>!<column> ==> <table>.<column>
4. trim(<value> ) ==> rtrim(ltrim(<value> ))
-oj
"Pancho" <Pancho@.discussions.microsoft.com> wrote in message
news:92287E29-C913-43A2-8FA5-0C0B7441CBB6@.microsoft.com...
> Hello,
> A colleague passed me this make-table query which works in Access, and
> we'd
> like to automate in SQL. I did some basic debugging but now on parse, SQL
> returns that Trim and Format are not recognized function nameS. I think
> you
> can see the what formatting is doing to provide a standard string length.
> Could someone advise what I need to do to get this to work in SQL? Any
> help
> would be much appreciated. Thanks, Pancho
> SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
> GVMOI2.TaxIDType,
> GVMOI2.ApplicationCode, GVMOI2.AccountNo,
> Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) &
> Trim(GVMOI2.TraceNbr) AS TraceNbrEdt, IIf(IsNumeric(GVMOI2.CreditAmtCash),
> Left(Format([CreditAmtCash],"0000000000.00"),10) &
> Right(Format([CreditAmtCash],"0000000000.00"),2),
> "000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2!DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) &
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10)
> &
> Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
> CreditAmtChecksFmt,
> IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10)
> &
> Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
> DebitAmtChecksFmt,
> GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
> GVMOI2.CheckReferenceNbr,
> GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
> GVMOI2.ThirdParty,
> "0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
> GVMOI2.IDNumber,
> GVMOI2.IDIssueBy, GVMOI2.IDOthers
> INTO MOI_Prep
> FROM GVMOI2;
>
>|||OJ,
Thank you for these clear instructions. I will try these tomorrow. Looks
good!
Best Wishes,
P
"oj" wrote:

> Follow the below guidelines to convert the query.
> 1. & ==> +
> 2. iif(<condition>,<true>,<false> ) ==> case when <condition> then <true>
> else <false> end
> 3. <table>!<column> ==> <table>.<column>
> 4. trim(<value> ) ==> rtrim(ltrim(<value> ))
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:92287E29-C913-43A2-8FA5-0C0B7441CBB6@.microsoft.com...
>
>|||Hi oj,
I replaced & with +, ! with . on table.column names, and
rtrim(ltrim(<value> ) parses OK now.
Pls take a look at the revised script. I don't quite follow how to change
the iif to case when. I am getting an incorrect syntax error near THEN.
Please let me know what I'm doing wrong on the first CASE line and I'll fix
the rest the same way. Thanks! P
SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
GVMOI2.TaxIDType,
GVMOI2.ApplicationCode, GVMOI2.AccountNo,
Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) +
RTrim(LTrim(GVMOI2.TraceNbr)) AS TraceNbrEdt,
CASE WHEN (IsNumeric(GVMOI2.CreditAmtCash)) THEN
Left(Format([CreditAmtCash],"0000000000.00"),10) +
Right(Format([CreditAmtCash],"0000000000.00"),2), ELSE FALSE
"000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2.DebitAmtCash),
Left(Format([DebitAmtCash],"0000000000.00"),10) +
Right(Format([DebitAmtCash],"0000000000.00"),2),
"000000000000") AS DebitAmtCashFmt,
IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10) +
Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
CreditAmtChecksFmt,
IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10) +
Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
DebitAmtChecksFmt,
GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
GVMOI2.CheckReferenceNbr,
GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
GVMOI2.ThirdParty,
"0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
GVMOI2.IDNumber,
GVMOI2.IDIssueBy, GVMOI2.IDOthers
INTO MOI_Prep
FROM GVMOI2;
"oj" wrote:

> Follow the below guidelines to convert the query.
> 1. & ==> +
> 2. iif(<condition>,<true>,<false> ) ==> case when <condition> then <true>
> else <false> end
> 3. <table>!<column> ==> <table>.<column>
> 4. trim(<value> ) ==> rtrim(ltrim(<value> ))
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:92287E29-C913-43A2-8FA5-0C0B7441CBB6@.microsoft.com...
>
>|||There is no format() in sqlserver. You'd want to use convert() instead.
IIf(IsNumeric(GVMOI2.DebitAmtCash),
Left(Format([DebitAmtCash],"0000000000.00"),10) +
Right(Format([DebitAmtCash],"0000000000.00"),2),
"000000000000") AS DebitAmtCashFmt,
==>
case when IsNumeric(GVMOI2.DebitAmtCash)=1 then
right(convert(varchar,convert(money,1000
0000000+GVMOI2.DebitAmtCash)),13)
else replicate('0',10) AS DebitAmtCashFmt,
-oj
"Pancho" <Pancho@.discussions.microsoft.com> wrote in message
news:E2C8FF99-A473-4D32-9BB2-59AEFF996FC9@.microsoft.com...
> Hi oj,
> I replaced & with +, ! with . on table.column names, and
> rtrim(ltrim(<value> ) parses OK now.
> Pls take a look at the revised script. I don't quite follow how to change
> the iif to case when. I am getting an incorrect syntax error near THEN.
> Please let me know what I'm doing wrong on the first CASE line and I'll
> fix
> the rest the same way. Thanks! P
> SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
> GVMOI2.TaxIDType,
> GVMOI2.ApplicationCode, GVMOI2.AccountNo,
> Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) +
> RTrim(LTrim(GVMOI2.TraceNbr)) AS TraceNbrEdt,
> CASE WHEN (IsNumeric(GVMOI2.CreditAmtCash)) THEN
> Left(Format([CreditAmtCash],"0000000000.00"),10) +
> Right(Format([CreditAmtCash],"0000000000.00"),2), ELSE FALSE
> "000000000000") AS CashCRFmt, IIf(IsNumeric(GVMOI2.DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) +
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> IIf(IsNumeric(GVMOI2. CreditAmtChecks),Left(Format([CreditAmtC
hecks],"0000000000.00"),10)
> +
> Right(Format([CreditAmtChecks],"0000000000.00"),2),"000000000000") AS
> CreditAmtChecksFmt,
> IIf(IsNumeric(GVMOI2. DebitAmtChecks),Left(Format([DebitAmtChe
cks],"0000000000.00"),10)
> +
> Right(Format([DebitAmtChecks],"0000000000.00"),2),"000000000000") AS
> DebitAmtChecksFmt,
> GVMOI2.TranCode, GVMOI2.TranName, GVMOI2.TellerID, GVMOI2.BranchNo,
> GVMOI2.CheckReferenceNbr,
> GVMOI2.CheckNbr, GVMOI2.BankNumber, GVMOI2.Remitter1, GVMOI2.Payee1,
> GVMOI2.ThirdParty,
> "0000000000000000000000000" AS DenominationFmt, GVMOI2.IDType,
> GVMOI2.IDNumber,
> GVMOI2.IDIssueBy, GVMOI2.IDOthers
> INTO MOI_Prep
> FROM GVMOI2;
>
> "oj" wrote:
>|||Thanks again oj. I have marked both of your posts as helpful and will try
this code.
Best Regards,
p
"oj" wrote:

> There is no format() in sqlserver. You'd want to use convert() instead.
> IIf(IsNumeric(GVMOI2.DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) +
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> ==>
> case when IsNumeric(GVMOI2.DebitAmtCash)=1 then
> right(convert(varchar,convert(money,1000
0000000+GVMOI2.DebitAmtCash)),13)
> else replicate('0',10) AS DebitAmtCashFmt,
>
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:E2C8FF99-A473-4D32-9BB2-59AEFF996FC9@.microsoft.com...
>
>|||oj,
This is getting closer but now I get an incorrect syntax near the word AS on
the last line of the section below:
SELECT GVMOI2.TranDateSold, GVMOI2.CustomerID, GVMOI2.TaxIDNum,
GVMOI2.TaxIDType,
GVMOI2.ApplicationCode, GVMOI2.AccountNo,
Left("00000000000000000000",20-Len(GVMOI2.TraceNbr)) +
RTrim(LTrim(GVMOI2.TraceNbr)) AS TraceNbrEdt,
CASE WHEN IsNumeric(GVMOI2.CreditAmtCash)=1 THEN
Right(Convert(varchar,convert(money,1000
000000000+GVMOI2.CreditAmtCash)),13)
ELSE
Replicate('0',13) AS CashCRFmt,
It looks like they want to name the column CreditAmtCash when there is a
numeric value and name it CashCRFmt when the value is non-numeric. Let me
know if I am using Replicate correctly.
Thanks,
p
"oj" wrote:

> There is no format() in sqlserver. You'd want to use convert() instead.
> IIf(IsNumeric(GVMOI2.DebitAmtCash),
> Left(Format([DebitAmtCash],"0000000000.00"),10) +
> Right(Format([DebitAmtCash],"0000000000.00"),2),
> "000000000000") AS DebitAmtCashFmt,
> ==>
> case when IsNumeric(GVMOI2.DebitAmtCash)=1 then
> right(convert(varchar,convert(money,1000
0000000+GVMOI2.DebitAmtCash)),13)
> else replicate('0',10) AS DebitAmtCashFmt,
>
> --
> -oj
>
> "Pancho" <Pancho@.discussions.microsoft.com> wrote in message
> news:E2C8FF99-A473-4D32-9BB2-59AEFF996FC9@.microsoft.com...
>
>

Converting Access 2000 Query - IIf statement to SQL Server 2000 Vi

I have a field in the query where I count the tech_area field. I have an Iif
(Count Of([tech_field])=0, CountOf([id]),CountOf[tech_field]).
My question is how do I translate that in SQL Server? I tried to write the
query using the new view window but I kept erroring when I put the IIf
statement in.
Any help would be greatly appreciated.
Thx,
CLM
You can use a Case expression instead. There is no IIF in
T-SQL or ANSI SQL. You can find more information and some
examples of using Case in SQL Server books online.
-Sue
On Mon, 21 Mar 2005 14:27:02 -0800, CLM
<CLM@.discussions.microsoft.com> wrote:

>I have a field in the query where I count the tech_area field. I have an Iif
>(Count Of([tech_field])=0, CountOf([id]),CountOf[tech_field]).
>My question is how do I translate that in SQL Server? I tried to write the
>query using the new view window but I kept erroring when I put the IIf
>statement in.
>Any help would be greatly appreciated.
>Thx,
>CLM

Converting Access 2000 Query - IIf statement to SQL Server 2000 Vi

I have a field in the query where I count the tech_area field. I have an Ii
f
(Count Of([tech_field])=0, CountOf([id]),CountOf[tech_field]).
My question is how do I translate that in SQL Server? I tried to write the
query using the new view window but I kept erroring when I put the IIf
statement in.
Any help would be greatly appreciated.
Thx,
CLMYou can use a Case expression instead. There is no IIF in
T-SQL or ANSI SQL. You can find more information and some
examples of using Case in SQL Server books online.
-Sue
On Mon, 21 Mar 2005 14:27:02 -0800, CLM
<CLM@.discussions.microsoft.com> wrote:

>I have a field in the query where I count the tech_area field. I have an I
if
>(Count Of([tech_field])=0, CountOf([id]),CountOf[tech_field]).
>My question is how do I translate that in SQL Server? I tried to write the
>query using the new view window but I kept erroring when I put the IIf
>statement in.
>Any help would be greatly appreciated.
>Thx,
>CLMsqlsql

Thursday, March 22, 2012

Converting a SQL Query to a Web page

I have a web site, and want to create a query on it using my current SQl database information, can someone explain to me how this is done? Or just send me a link to where I can get the information.
ThanksI am not entirely sure what you mean. Do you wish to
execute a query from the web site to retrieve data from
the database or send an update query to the database? Or
something else? Also, which server side technology are
you using for the web site? (PHP, ASP, ASP.NET, etc)
David Grant
>--Original Message--
>I have a web site, and want to create a query on it
using my current SQL database information, can someone
explain to me how this is done? Or just send me a link
to where I can get the information.
>Thanks
>.
>

converting a query with *= into SQL 92

i have a query which goes like this:-

select a.col1,b.col2,c.col2
from tab1 a,tab2 b,tab3 c
where
a.col1 *= b.col1 and
a.col2 *= c.col2 and
b.col3 = c.col3

how do I write this query in SQL 92?

also can we replace *= with =* by interchanging the participating tables as in

"a.col1 *= b.col1" is this same as "b.col1 =* a.col1"One of the problems with the SQL89 join syntax is that different RDBMSs may
execute the query differently when both inner and outer join predicates are
specified. Test the following out to see if it gives the result you expect.

SELECT A.col1, B.col2, C.col2
FROM Tab1 AS A
LEFT JOIN Tab2 AS B
ON A.col1 = B.col1
LEFT JOIN Tab3 AS C
ON A.col2 = C.col2 AND B.col3 = C.col3

> also can we replace *= with =* by interchanging the participating tables
as in

If you specify an inner join as well then this might give different results
to your original query. It depends on the order in which the joins are
performed. Use LEFT JOIN / RIGHT JOIN / INNER JOIN instead.

--
David Portas
SQL Server MVP
--|||Here is how OUTER JOINs work in SQL-92. Assume you are given:

Table1 Table2
a b a c
====== ======
1 w 1 r
2 x 2 s
3 y 3 t
4 z

and the outer join expression:

Table1
LEFT OUTER JOIN
Table2
ON Table1.a = Table2.a <== join condition
AND Table2.c = 't'; <== single table condition

We call Table1 the "preserved table" and Table2 the "unpreserved
table" in the query. What I am going to give you is a little
different, but equivalent to the ANSI/ISO standards.

1) We build the CROSS JOIN of the two tables. Scan each row in the
result set.

2) If the predicate tests TRUE for that row, then you keep it. You
also remove all rows derived from it from the CROSS JOIN

3) If the predicate tests FALSE or UNKNOWN for that row, then keep the
columns from the preserved table, convert all the columns from the
unpreserved table to NULLs and remove the duplicates.

So let us execute this by hand:

Let @. = passed the first predicate
Let * = passed the second predicate

Table1 CROSS JOIN Table2
a b a c
=========================
1 w 1 r @.
1 w 2 s
1 w 3 t *
2 x 1 r
2 x 2 s @.
2 x 3 t *
3 y 1 r
3 y 2 s
3 y 3 t @.* <== the TRUE set
4 z 1 r
4 z 2 s
4 z 3 t *

Table1 LEFT OUTER JOIN Table2
a b a c
=========================
3 y 3 t <= only TRUE row
--------
1 w NULL NULL Sets of duplicates
1 w NULL NULL
1 w NULL NULL
--------
2 x NULL NULL
2 x NULL NULL
2 x NULL NULL
3 y NULL NULL <== derived from the TRUE set - Remove
3 y NULL NULL
--------
4 z NULL NULL
4 z NULL NULL
4 z NULL NULL

the final results:

Table1 LEFT OUTER JOIN Table2
a b a c
=========================
1 w NULL NULL
2 x NULL NULL
3 y 3 t
4 z NULL NULL

The basic rule is that every row in the preserved table is represented
in the results in at least one result row.

There are limitations and very serious problems with the extended
equality version of an outer join used in some diseased mutant
products. Consider the two Chris Date tables

Suppliers SupParts
supno supno partno qty
========= ==============
S1 S1 P1 100
S2 S1 P2 250
S3 S2 P1 100
S2 P2 250

and let's do an extended equality outer join like this:

SELECT *
FROM Supplier, SupParts
WHERE Supplier.supno *= SupParts.supno
AND qty < 200;

If I do the outer first, I get:

Suppliers LOJ SupParts
supno supno partno qty
=======================
S1 S1 P1 100
S1 S1 P2 250
S2 S2 P1 100
S2 S2 P2 250
S3 NULL NULL NULL

Then I apply the (qty < 200) predicate and get

Suppliers LOJ SupParts
supno supno partno qty
===================
S1 S1 P1 100
S2 S2 P1 100

Doing it in the opposite order

Suppliers LOJ SupParts
supno supno partno qty
===================
S1 S1 P1 100
S2 S2 P1 100
S3 NULL NULL NULL

Sybase does it one way, Oracle does it the other and Centura (nee
Gupta) lets you pick which one -- the worst of both non-standard
worlds! In SQL-92, you have a choice and can force the order of
execution. Either do the predicates after the join ...

SELECT *
FROM Supplier
LEFT OUTER JOIN
SupParts
ON Supplier.supno = SupParts.supno
WHERE qty < 200;

... or do it in the joining:

SELECT *
FROM Supplier
LEFT OUTER JOIN
SupParts
ON Supplier.supno = SupParts.supno
AND qty < 200;

Another problem is that you cannot show the same table as preserved
and unpreserved in the extended equality version, but it is easy in
SQL-92. For example to find the students who have taken Math 101 and
might have taken Math 102:

SELECT C1.student, C1.math, C2.math
FROM (SELECT * FROM Courses WHERE math = 101) AS C1
LEFT OUTER JOIN
(SELECT * FROM Courses WHERE math = 102) AS C2
ON C1.student = C2.student;

Converting a longer query into SQL92 syntax?

First of all, I DON'T want to convert the following query into the SQL92
equivalent, I just want to learn how to do it.
Most of the left and right join examples I've found on the Net usually deal
with 2 or three tables at the maximum. What happens if my query uses 7
tables and only two of those require a left join? The 1st Where clause
requires the left join; everything else stays the same. That's one of the
reasons I still haven't switched to SQL92. This is the query that I want to
convert:
select addr.city, addr.secondary_addr, count(*)
from
addr, acct_offer_prod, acct, cust, active_addr_range, vw_bdry_levels,
addr_range_grouping
where
addr.addr_id = acct_offer_prod.addr_id and
acct_offer_prod.acct_id = acct.acct_id and
acct.acct_id = cust.cust_id and
acct_offer_prod.addr_id = active_addr_range.addr_id and
active_addr_range.range_id = addr_range_grouping.range_id and
addr_range_grouping.bdry_id = vw_bdry_levels.bdry_id and
vw_bdry_levels.metro_or_isla like 'HD ISLA' and
vw_bdry_levels.region_short like 'REG-R' and
vw_bdry_levels.district_short like '037' and
acct_offer_prod.addr_id = addr.addr_id and
active_addr_range.eff_dt <= getdate() and
(active_addr_range.exp_dt >= getdate() or active_addr_range.exp_dt is null)
and
addr_range_grouping.eff_dt <= getdate() and
(addr_range_grouping.exp_dt >= getdate() or addr_range_grouping.exp_dt is
null) and vw_bdry_levels.eff_dt <= getdate() and
(vw_bdry_levels.exp_dt >= getdate() or vw_bdry_levels.exp_dt is null) and
acct_offer_prod.del_status_cd = 'NORMAL'
group by addr.city, addr.secondary_addrYour query is already valid SQL92 syntax (except for the non-standard
GETDATE function).
I assume you are referring to replacing the *= / =* notation with the LEFT /
RIGHT JOIN syntax. To do that just requires that you move the joining
criteria into the ON clause rather than the WHERE clause. In principle you
can mix LEFT and INNER JOINs as much as you like in a SELECT statement. The
key point is what goes in the ON clauses.
I'm not really clear what you are asking for so maybe we can help you better
if you post an example. Please do include DDL (CREATE TABLE statement(s)
including keys and constraints) with any query you post.
David Portas
SQL Server MVP
--|||> First of all, I DON'T want to convert the following query into the SQL92
> equivalent, I just want to learn how to do it.
> Most of the left and right join examples I've found on the Net usually dea
l
> with 2 or three tables at the maximum. What happens if my query uses 7
> tables and only two of those require a left join? The 1st Where clause
> requires the left join; everything else stays the same. That's one of the
> reasons I still haven't switched to SQL92. This is the query that I want t
o
> convert:
First of all, let's write it so it's readable. Looking past the naming
convention and the nonsense of putting keywords in all caps, this should be
SQL92 equivalent of your original query (and will work in SQL Server).
Select A.City, A.Secondary_Addr, Count(*)
From Addr As A
Join Acct_Offer_Prod As AOP
On A.Addr_Id = AOP.Addr_Id
And AOP.Del_Status_Cd = 'NORMAL'
Join Cust As C
On A.Acct_Id = C.Cust_Id
Join Active_Addr_Range As AAR
On AOP.Addr_Id = AAR.Addr_Id
And AAR.Eff_Dt <= Current_Timestamp
And (AAR.Exp_Dt >= Current_Timestamp
Or AAR.Exp_Dt Is Null)
Join Addr_Range_Grouping As ARG
On ARG.Range_Id = AAR.Range_Id
And ARG.Eff_Dt <= Current_Timestamp
And (ARG.Exp_Dt >= Current_Timestamp
Or ARG.Exp_Dt Is Null)
Join vw_Bdry_Levels As VBL
On ARG.Bdry_Id = BDry_Id
And VBL.Metro_Or_Isla Like 'HD ISLA'
And VBL.Region_Short Like 'REG-R'
And VBL.District_Short Like '037'
And VBL.Eff_Dt <= Current_Timestamp
And (VBL.Exp_Dt >= Current_Timestamp
Or VBL.Exp_Dt Is Null)
Group By A.City, A.Secondary_Addr

> The 1st Where clause
> requires the left join; everything else stays the same. That's one of the
> reasons I still haven't switched to SQL92. This is the query that I want t
o
> convert:
Are you asking, "What will happen *if* the first where clause needs to be
converted into a left join?" If that is the case there are a couple of
solutions, I'd be inclined to write like so (depending on the actual spec of
what is desired) using paren'ed joins (Not sure if this is officially ANSI
compliant)
Select A.City, A.Secondary_Addr, Count(*)
From Addr As A
Join Cust As C
On A.Acct_Id = C.Cust_Id
Left Join (Acct_Offer_Prod As AOP
Join Active_Addr_Range As AAR
On AOP.Addr_Id = AAR.Addr_Id
And AAR.Eff_Dt <= Current_Timestamp
And (AAR.Exp_Dt >= Current_Timestamp
Or AAR.Exp_Dt Is Null)
Join Addr_Range_Grouping As ARG
On ARG.Range_Id = AAR.Range_Id
And ARG.Eff_Dt <= Current_Timestamp
And (ARG.Exp_Dt >= Current_Timestamp
Or ARG.Exp_Dt Is Null)
Join vw_Bdry_Levels As VBL
On ARG.Bdry_Id = BDry_Id
And VBL.Metro_Or_Isla Like 'HD ISLA'
And VBL.Region_Short Like 'REG-R'
And VBL.District_Short Like '037'
And VBL.Eff_Dt <= Current_Timestamp
And (VBL.Exp_Dt >= Current_Timestamp
Or VBL.Exp_Dt Is Null))
On A.Addr_Id = AOP.Addr_Id
And AOP.Del_Status_Cd = 'NORMAL'
Group By A.City, A.Secondary_Addr
Another solution is to use a series of Left Joins
Select A.City, A.Secondary_Addr, Count(*)
From Addr As A
Join Cust As C
On A.Acct_Id = C.Cust_Id
Left Join Acct_Offer_Prod As AOP
On A.Addr_Id = AOP.Addr_Id
And AOP.Del_Status_Cd = 'NORMAL'
Left Join Active_Addr_Range As AAR
On AOP.Addr_Id = AAR.Addr_Id
And AAR.Eff_Dt <= Current_Timestamp
And (AAR.Exp_Dt >= Current_Timestamp
Or AAR.Exp_Dt Is Null)
Left Join Addr_Range_Grouping As ARG
On ARG.Range_Id = AAR.Range_Id
And ARG.Eff_Dt <= Current_Timestamp
And (ARG.Exp_Dt >= Current_Timestamp
Or ARG.Exp_Dt Is Null)
Left Join vw_Bdry_Levels As VBL
On ARG.Bdry_Id = BDry_Id
And VBL.Metro_Or_Isla Like 'HD ISLA'
And VBL.Region_Short Like 'REG-R'
And VBL.District_Short Like '037'
And VBL.Eff_Dt <= Current_Timestamp
And (VBL.Exp_Dt >= Current_Timestamp
Or VBL.Exp_Dt Is Null)
Group By A.City, A.Secondary_Addr
The results of these two solutions can vary dramatically depending on what i
s
actually desired. Thus, I'd need more details about the actual results desir
ed
before I could provide an exact solution.
Thomas|||That's really my doubt: taking the first joining critera from the WHERE
clause and moving it to the ON clause. Based on your description, it would
look like the following - but won't it alter the resultset since I've swiche
d
all the tables around?
select addr.city, addr.secondary_addr, count(*)
from
acct, cust, active_addr_range, vw_bdry_levels, addr_range_grouping, addr
LEFT JOIN acct_offer_prod on
(addr.addr_id = acct_offer_prod.addr_id)
where
acct_offer_prod.acct_id = acct.acct_id and ...
...
What if my query uses 50 tables and 200 JOINS, would the order of the tables
and/or JOINS alter the resulting recordset?
Thanks.
"David Portas" wrote:

> Your query is already valid SQL92 syntax (except for the non-standard
> GETDATE function).
> I assume you are referring to replacing the *= / =* notation with the LEFT
/
> RIGHT JOIN syntax. To do that just requires that you move the joining
> criteria into the ON clause rather than the WHERE clause. In principle you
> can mix LEFT and INNER JOINs as much as you like in a SELECT statement. Th
e
> key point is what goes in the ON clauses.
> I'm not really clear what you are asking for so maybe we can help you bett
er
> if you post an example. Please do include DDL (CREATE TABLE statement(s)
> including keys and constraints) with any query you post.
> --
> David Portas
> SQL Server MVP
> --
>
>|||On Tue, 10 May 2005 12:54:06 -0700, VMI wrote:

>First of all, I DON'T want to convert the following query into the SQL92
>equivalent, I just want to learn how to do it.
>Most of the left and right join examples I've found on the Net usually deal
>with 2 or three tables at the maximum. What happens if my query uses 7
>tables and only two of those require a left join? The 1st Where clause
>requires the left join; everything else stays the same. That's one of the
>reasons I still haven't switched to SQL92. This is the query that I want to
>convert:
(snip)
Hi VMI,
Are you sure you posted the right query? Since I can find no =* or *=
operator, the query you posted consists solely of INNER JOINs. BTW, why
are you using LIKE for string comparisons when the string constant you
compare to doesn't use any wildcards?
Anyway, here's what I believe would be the equivalent of your query in
the infixed join notation. Note that I also removed the duplicate check
for equality between acct_offer_prod.addr_id and addr.addr_id.
SELECT addr.city, addr.secondary_addr, COUNT(*)
FROM addr
INNER JOIN acct_offer_prod
ON acct_offer_prod.addr_id = addr.addr_id
INNER JOIN acct
ON acct.acct_id = acct_offer_prod.acct_id
INNER JOIN cust
ON cust.cust_id = acct.acct_id
INNER JOIN active_addr_range
ON active_addr_range.addr_id = acct_offer_prod.addr_id
INNER JOIN addr_range_grouping
ON addr_range_grouping.range_id = active_addr_range.range_id
INNER JOIN vw_bdry_levels
ON vw_bdry_levels.bdry_id = addr_range_grouping.bdry_id
WHERE vw_bdry_levels.metro_or_isla = 'HD ISLA'
AND vw_bdry_levels.region_short = 'REG-R'
AND vw_bdry_levels.district_short = '037'
AND active_addr_range.eff_dt <= CURRENT_TIMESTAMP
AND ( active_addr_range.exp_dt >= CURRENT_TIMESTAMP
OR active_addr_range.exp_dt IS NULL)
AND addr_range_grouping.eff_dt <= CURRENT_TIMESTAMP
AND ( addr_range_grouping.exp_dt >= CURRENT_TIMESTAMP
OR addr_range_grouping.exp_dt IS NULL)
AND vw_bdry_levels.eff_dt <= CURRENT_TIMESTAMP
AND ( vw_bdry_levels.exp_dt >= CURRENT_TIMESTAMP
OR vw_bdry_levels.exp_dt is null)
AND acct_offer_prod.del_status_cd = 'NORMAL'
GROUP BY addr.city, addr.secondary_addr
(untested)
Note: for better readability, I would consider rewriting the checks for
effective date / expiry date as
AND CURRENT_TIMESTAMP BETWEEN active_addr_range.eff_dt
AND COALESCE (active_addr_range.exp_dt,
CURRENT_TIMESTAMP)
But of course, readability can be a pretty personal opinion :-)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||If you simply threw in a Left Join, in the place you described, you would no
t
alter the results. The reason is you have criteria in the where clause on th
e
derived tables. That effectively makes them into inner joins. So, in this ca
se,
the criteria of Del_Status_Cd = 'Normal' would essentially cause the system
to
ignore your left join.
It's not so much the order of the tables as it is how you are applying your
criteria.
Thomas
"VMI" <VMI@.discussions.microsoft.com> wrote in message
news:EAEA96BA-1655-4A4F-AA46-D65AAD0BDBA9@.microsoft.com...
> That's really my doubt: taking the first joining critera from the WHERE
> clause and moving it to the ON clause. Based on your description, it would
> look like the following - but won't it alter the resultset since I've swic
hed
> all the tables around?
> select addr.city, addr.secondary_addr, count(*)
> from
> acct, cust, active_addr_range, vw_bdry_levels, addr_range_grouping, addr
> LEFT JOIN acct_offer_prod on
> (addr.addr_id = acct_offer_prod.addr_id)
> where
> acct_offer_prod.acct_id = acct.acct_id and ...
> ...
> What if my query uses 50 tables and 200 JOINS, would the order of the tabl
es
> and/or JOINS alter the resulting recordset?
> Thanks.
>
> "David Portas" wrote:
>|||Conceptually. each "Join" is a join between only two "Relations", or
"Resultsets". When you have more than two tables in a From Clause, and,
therefore, you have two or more joins. the second "Join" that takes place ca
n
be thought of as a Join between the intermediate resultset created by the
first join, and the third table. So the answer to your question depends on
what order, and what exactly, you wish to Join in this second Join...
With three tables, for example, Two possibilities exist:
You could Join Tables B to A, using Outer Join syntax, and then Join C to
that resultset, also using Outer Join SyntAX...
From TableA
Left Outer Join Table B On .....
Left Outer Join Table C On ......
Or 2) you might be wishing to Join the COmbined Inner Join of Tables B & C
to Table A. In this case you would be joining B & C FIrst, and then Joining
THAT resultset to TableA using Outer Join Syntax
From TableA
Left Outer Join (Table B Join Table C On ....)
On ....
This approach might be used to get ALL Customers, (even the ones with no
Invoices), plus the data from a Invoices and connected Invoice Details table
s
, but only include invoices that have details...
"VMI" wrote:

> First of all, I DON'T want to convert the following query into the SQL92
> equivalent, I just want to learn how to do it.
> Most of the left and right join examples I've found on the Net usually dea
l
> with 2 or three tables at the maximum. What happens if my query uses 7
> tables and only two of those require a left join? The 1st Where clause
> requires the left join; everything else stays the same. That's one of the
> reasons I still haven't switched to SQL92. This is the query that I want t
o
> convert:
> select addr.city, addr.secondary_addr, count(*)
> from
> addr, acct_offer_prod, acct, cust, active_addr_range, vw_bdry_levels,
> addr_range_grouping
> where
> addr.addr_id = acct_offer_prod.addr_id and
> acct_offer_prod.acct_id = acct.acct_id and
> acct.acct_id = cust.cust_id and
> acct_offer_prod.addr_id = active_addr_range.addr_id and
> active_addr_range.range_id = addr_range_grouping.range_id and
> addr_range_grouping.bdry_id = vw_bdry_levels.bdry_id and
> vw_bdry_levels.metro_or_isla like 'HD ISLA' and
> vw_bdry_levels.region_short like 'REG-R' and
> vw_bdry_levels.district_short like '037' and
> acct_offer_prod.addr_id = addr.addr_id and
> active_addr_range.eff_dt <= getdate() and
> (active_addr_range.exp_dt >= getdate() or active_addr_range.exp_dt is null
)
> and
> addr_range_grouping.eff_dt <= getdate() and
> (addr_range_grouping.exp_dt >= getdate() or addr_range_grouping.exp_dt is
> null) and vw_bdry_levels.eff_dt <= getdate() and
> (vw_bdry_levels.exp_dt >= getdate() or vw_bdry_levels.exp_dt is null) and
> acct_offer_prod.del_status_cd = 'NORMAL'
> group by addr.city, addr.secondary_addr
>
>|||>> First of all, let's write it so it's readable. Looking past the
naming convention and the nonsense of putting keywords in all caps, ..
<<
Upon how amny years of research do you base this statement, if any?
I just published a book (SQL PROGRAMMING STYLE) based on 20+ years of
"readability of code" research, some of which I myself did at AIRMICS.
Reserved words in uppercase were shown in *every* study to be easier to
read than code in all-lowercase or all-uppercase. I think in the late
1970's we had about 150+ of them -- it was a popular topic for grad
students (see Ben Schneiderman at U. of Maryland, et al).
Quick lecture.
1) The eye of a Latin alphabet reader is drawn to an uppercase letter;
it is the start of a sentence which models a unit of thought.
Camelcase screws up eye movement. Lowercase does not attract it.
2) All uppercase words are seen as bouma. Bet that you had no idea
what a "bouma" is because you never did research on code readability.
It is "word shape" -- google it.for details. We do not read code the
way we read text. Code is 3D and text is linear.
You are smarter than this! Send me a "snail mail" and I will get you a
copy of SQL PROGRAMMING STYLE.|||1) Why are your using LIKE with patterns that have no wildcards? Do you
like the overhead?
2) Why are you still saying getdate() when you mean CURRENT_TIMESTAMP
? Or do you spit on all standards?
3) Why do you put AND at the end of lines, which only makes the code a
screaming XXXXX to maintain? think about how the eye has to jerk to
the end of the previous line.
4) Here is how OUTER JOINs work in SQL-92. Assume you are given:
Table1 Table2
a b a c
====== ======
1 w 1 r
2 x 2 s
3 y 3 t
4 z
and the outer join expression:
Table1
LEFT OUTER JOIN
Table2
ON Table1.a = Table2.a <== join condition
AND Table2.c = 't'; <== single table condition
We call Table1 the "preserved table" and Table2 the "unpreserved table"
in the query. What I am going to give you is a little different, but
equivalent to the ANSI/ISO standards.
1) We build the CROSS JOIN of the two tables. Scan each row in the
result set.
2) If the predicate tests TRUE for that row, then you keep it. You also
remove all rows derived from it from the CROSS JOIN
3) If the predicate tests FALSE or UNKNOWN for that row, then keep the
columns from the preserved table, convert all the columns from the
unpreserved table to NULLs and remove the duplicates.
So let us execute this by hand:
Let @. = passed the first predicate
Let * = passed the second predicate
Table1 CROSS JOIN Table2
a b a c
=========================
1 w 1 r @.
1 w 2 s
1 w 3 t *
2 x 1 r
2 x 2 s @.
2 x 3 t *
3 y 1 r
3 y 2 s
3 y 3 t @.* <== the TRUE set
4 z 1 r
4 z 2 s
4 z 3 t *
Table1 LEFT OUTER JOIN Table2
a b a c
=========================
3 y 3 t <= only TRUE row
--
1 w NULL NULL Sets of duplicates
1 w NULL NULL
1 w NULL NULL
--
2 x NULL NULL
2 x NULL NULL
2 x NULL NULL
3 y NULL NULL <== derived from the TRUE set - Remove
3 y NULL NULL
--
4 z NULL NULL
4 z NULL NULL
4 z NULL NULL
the final results:
Table1 LEFT OUTER JOIN Table2
a b a c
=========================
1 w NULL NULL
2 x NULL NULL
3 y 3 t
4 z NULL NULL
The basic rule is that every row in the preserved table is represented
in the results in at least one result row.
There are limitations and very serious problems with the extended
equality version of an outer join used in some diseased mutant
products. Consider the two Chris Date tables
Suppliers SupParts
supno supno partno qty
========= ==============
S1 S1 P1 100
S2 S1 P2 250
S3 S2 P1 100
S2 P2 250
and let's do an extended equality outer join like this:
SELECT *
FROM Supplier, SupParts
WHERE Supplier.supno *= SupParts.supno
AND qty < 200;
If I do the outer first, I get:
Suppliers LOJ SupParts
supno supno partno qty
=======================
S1 S1 P1 100
S1 S1 P2 250
S2 S2 P1 100
S2 S2 P2 250
S3 NULL NULL NULL
Then I apply the (qty < 200) predicate and get
Suppliers LOJ SupParts
supno supno partno qty
===================
S1 S1 P1 100
S2 S2 P1 100
Doing it in the opposite order
Suppliers LOJ SupParts
supno supno partno qty
===================
S1 S1 P1 100
S2 S2 P1 100
S3 NULL NULL NULL
Sybase does it one way, Oracle does it the other and Centura (nee
Gupta) lets you pick which one -- the worst of both non-standard
worlds! In SQL-92, you have a choice and can force the order of
execution. Either do the predicates after the join ...
SELECT *
FROM Supplier
LEFT OUTER JOIN
SupParts
ON Supplier.supno = SupParts.supno
WHERE qty < 200;
.. or do it in the joining:
SELECT *
FROM Supplier
LEFT OUTER JOIN
SupParts
ON Supplier.supno = SupParts.supno
AND qty < 200;
Another problem is that you cannot show the same table as preserved and
unpreserved in the extended equality version, but it is easy in SQL-92.
For example to find the students who have taken Math 101 and might
have taken Math 102:
SELECT C1.student, C1.math, C2.math
FROM (SELECT * FROM Courses WHERE math = 101) AS C1
LEFT OUTER JOIN
(SELECT * FROM Courses WHERE math = 102) AS C2
ON C1.student = C2.student;|||>> First of all, let's write it so it's readable. Looking past the
> Upon how amny years of research do you base this statement, if any?
I'd say about ten years. That's about how long color coded editors have been
available.

> I just published a book (SQL PROGRAMMING STYLE) based on 20+ years of
> "readability of code" research, some of which I myself did at AIRMICS.
> Reserved words in uppercase were shown in *every* study to be easier to
> read than code in all-lowercase or all-uppercase. I think in the late
> 1970's we had about 150+ of them -- it was a popular topic for grad
> students (see Ben Schneiderman at U. of Maryland, et al).
Really. So if everything is upper case that is easier? Come in to the 21st
century. Do these studies account for high resolution monitors and color cod
ing?
A lot has happened since the 1970's.

> Quick lecture.
> 1) The eye of a Latin alphabet reader is drawn to an uppercase letter;
> it is the start of a sentence which models a unit of thought.
> Camelcase screws up eye movement. Lowercase does not attract it.
Which is why I use pascal casing for keywords not camel casing. Besides, it
would be silly to write sElect * fRom tAbleName wHere cOlumnName > 10.

> 2) All uppercase words are seen as bouma. Bet that you had no idea
> what a "bouma" is because you never did research on code readability.
> It is "word shape" -- google it.for details. We do not read code the
> way we read text. Code is 3D and text is linear.
Admittedly, before you mentioned this, no I did not know what "bouma" meant.
However, after doing some reasearch, I did find this:
" The second key piece of experimental data to support the word shape model
is
that lowercase text is read faster than uppercase text. Woodworth (1938) was
the
first to report this finding in his influential textbook Experimental
Psychology. This finding has been confirmed more recently by Smith (1969) an
d
Fisher (1975). Participants were asked to read comparable passages of text,
half
completely in uppercase text and half presented in standard lowercase text.
In
each study, participants read reliably faster with the lowercase text by a 5
-10%
speed difference. This supports the word shape model because lowercase text
enables unique patterns of ascending, descending, and neutral characters. Wh
en
text is presented in all uppercase, all letters have the same text size and
thus
are more difficult and slower to read. "
From
http://www.microsoft.com/typography...ecognition.aspx

> You are smarter than this! Send me a "snail mail" and I will get you a
> copy of SQL PROGRAMMING STYLE.
Smart people know that they know only a fraction of what there is to know. I
'm
always amenable to learning more and re-evaluating what I think I know. Can
you
get me more than the 20% discount offered by Morgan Kaufmann? To where would
I
send said snail mail request? :->
Thomassqlsql

Converting a field from int to varchar during query

I have a query where I am writing the following statement:
select * from .....
where table1.field1 = table2.field2
....
....
....
field2 is a varchar field and field1 is an int field. Field2 contains the
data mapping data for field1 and also other unrelated data as character
strings.
How do I run this query without getting the error - "Syntax error converting
the varchar value 'XXXX' to a column of data type int."
Thanks,
Jignesh.
On Wed, 2 Feb 2005 13:07:04 -0800, Jig Bhakta wrote:

>I have a query where I am writing the following statement:
>select * from .....
>where table1.field1 = table2.field2
>...
>...
>...
>field2 is a varchar field and field1 is an int field. Field2 contains the
>data mapping data for field1 and also other unrelated data as character
>strings.
>How do I run this query without getting the error - "Syntax error converting
>the varchar value 'XXXX' to a column of data type int."
Hi Jignesh,
Try:
select * from .....
where CAST(table1.field1 AS varchar(10)) = table2.field2
....
....
....
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Nope, still getting the error.
"Hugo Kornelis" wrote:

> On Wed, 2 Feb 2005 13:07:04 -0800, Jig Bhakta wrote:
>
> Hi Jignesh,
> Try:
> select * from .....
> where CAST(table1.field1 AS varchar(10)) = table2.field2
> ....
> ....
> ....
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>
|||On Thu, 3 Feb 2005 13:01:08 -0800, Jig Bhakta wrote:

>Nope, still getting the error.
Hi Jignesh,
In that case, you better post the complete query. Best is to include
CREATE TABLE statements and INSERT statements with some sample data to
reproduce the error.
Here's a small script that shows that my change does work on my system, so
your error is either caused by something else in your query, by something
strange in your data or by a SQL Server bug. If you post a script that
will reproduce the error, we can find which of these three is the cause.
-- Start of repro script that show the error is corrected
create table table1 (field1 int not null)
create table table2 (field2 varchar(20) not null)
go
insert table1 (field1) select 1 union all select 2
insert table2 (field2) select '1' union all select 'XXXX'
go
print 'Original'
print ''
select * from table1, table2
where table1.field1 = table2.field2
print '--'
go
print ''
print 'Corrected'
print ''
select * from table1, table2
where CAST(table1.field1 AS varchar(10)) = table2.field2
print '--'
go
drop table table1
drop table table2
go
-- Output:
Original
field1 field2
-- --
1 1
Server: Msg 245, Level 16, State 1, Line 3
Syntax error converting the varchar value 'XXXX' to a column of data type
int.
Corrected
field1 field2
-- --
1 1
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Jig,
Try this:
select * from ...
where
case when table1.field1 not like '%[^0-9]%' then cast(table1.field1 as
int) end
= table2.field2
The reason for the error is that a varchar = integer comparison
causes the varchar to be converted to an integer, so XXXX is
getting converted to an integer for the comparison. The CASE
statement causes the query to compare the column field1 with
field2 only if field1 is all digits. Otherwise, it compares NULL, which
won't cause an error.
The best thing to do would be not to store numerical and character
data in the same column! If it makes sense to compare two columns,
but they are not the same type, it's usually a sign that the database design
can be improved.
Steve Kass
Drew University
Jig Bhakta wrote:

>I have a query where I am writing the following statement:
>select * from .....
>where table1.field1 = table2.field2
>...
>...
>...
>field2 is a varchar field and field1 is an int field. Field2 contains the
>data mapping data for field1 and also other unrelated data as character
>strings.
>How do I run this query without getting the error - "Syntax error converting
>the varchar value 'XXXX' to a column of data type int."
>Thanks,
>Jignesh.
>