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

Thursday, March 29, 2012

Convert AlphaNumeric to Numeric

Hello,

I have to convert a alpha numeric value to a numeric value using query.
Is there a way to do it.

The column data type is Varchar and I am storing alpha numeric values to it.
I have to sort the column now. when I say order by [column name] it is not comming properly.

Need some solution to do it.

Regards,
GowriShankar.

Quote:

Originally Posted by gowrishankar

Hello,

I have to convert a alpha numeric value to a numeric value using query.
Is there a way to do it.

The column data type is Varchar and I am storing alpha numeric values to it.
I have to sort the column now. when I say order by [column name] it is not comming properly.

Need some solution to do it.

Regards,
GowriShankar.


What do you mean by "alphanumeric value"? Do you have non-numeric chars in the column? If yes, how do you expect it to be converted to numeric? If no, then use "convert(int, ColumnName)" or "cast(ColumnName as int)" statements.
Please post examples|||

Quote:

Originally Posted by almaz

What do you mean by "alphanumeric value"? Do you have non-numeric chars in the column? If yes, how do you expect it to be converted to numeric? If no, then use "convert(int, ColumnName)" or "cast(ColumnName as int)" statements.
Please post examples


try like this
SELECT Description
FROM ModuleSetup
ORDER BY CAST(Description AS varchar)

Convert Access Query w/IIF to SQL Server View

I am brand new to SQL Server. I had to move my data tables from Access 2003
onto SQL Server 2000. I have just upsized my .mdb using the upsizing wizard
and, after some minor changes, have gotten everything to work.
Now, I'm trying to focus on speeding things up. I have several nested
queries, using many tables, with several IIF statements that are used just
for selecting data to be displayed on forms and reports. I attempted to
convert one into a view, but have discovered that views don't allow IIF
statements. Is there a better way to do this? Can you create a procedure tha
t
is linked to Access? How do you reference this in Access?(c) Access' IIF translates to the CASE expression in SQL Server. See
http://www.aspfaq.com/2214 for this and other resources that should prove
handy.
(b) create your view using Query Analyzer; if you use Enterprise Mangler's
view editor, you won't be able to use CASE (among other problems).
"Holly" <Holly@.discussions.microsoft.com> wrote in message
news:DB695ADD-7A5D-44A4-8417-D7E6A3C40277@.microsoft.com...
>I am brand new to SQL Server. I had to move my data tables from Access 2003
> onto SQL Server 2000. I have just upsized my .mdb using the upsizing
> wizard
> and, after some minor changes, have gotten everything to work.
> Now, I'm trying to focus on speeding things up. I have several nested
> queries, using many tables, with several IIF statements that are used just
> for selecting data to be displayed on forms and reports. I attempted to
> convert one into a view, but have discovered that views don't allow IIF
> statements. Is there a better way to do this? Can you create a procedure
> that
> is linked to Access? How do you reference this in Access?|||(c) Access' IIF translates to the CASE expression in SQL Server. See
http://www.aspfaq.com/2214 for this and other resources that should prove
handy.
(b) create your view using Query Analyzer; if you use Enterprise Mangler's
view editor, you won't be able to use CASE (among other problems).
"Holly" <Holly@.discussions.microsoft.com> wrote in message
news:DB695ADD-7A5D-44A4-8417-D7E6A3C40277@.microsoft.com...
>I am brand new to SQL Server. I had to move my data tables from Access 2003
> onto SQL Server 2000. I have just upsized my .mdb using the upsizing
> wizard
> and, after some minor changes, have gotten everything to work.
> Now, I'm trying to focus on speeding things up. I have several nested
> queries, using many tables, with several IIF statements that are used just
> for selecting data to be displayed on forms and reports. I attempted to
> convert one into a view, but have discovered that views don't allow IIF
> statements. Is there a better way to do this? Can you create a procedure
> that
> is linked to Access? How do you reference this in Access?|||Thanks for the speedy response. Another question: If I create my view using
query analyzer, how do I save it as a query to link to Access?|||If you have a view in SQL Server, like:
CREATE VIEW dbo.MyView
AS
SELECT 1;
Then from Access you can just treat it like a table, e.g. SELECT * FROM
dbo.MyView instead of SELECT * FROM dbo.MyTable.
"Holly" <Holly@.discussions.microsoft.com> wrote in message
news:D6BF7042-48B7-4FC0-9EE2-D66026A461D7@.microsoft.com...
> Thanks for the speedy response. Another question: If I create my view
> using
> query analyzer, how do I save it as a query to link to Access?|||Sorry, I'm not following you.
Ok, using SQL Query Analyzer, I created my Select statement using the case
statements instead of IIF's, and parsing completed successfully. It runs and
selects the right information. Now what?
Do I have to save this somewhere special? Then what.|||You do not save it somewhere else. View is a server object, meaning it has
to be created on the SQL Server database (and saved there after creating
it).
"Holly" <Holly@.discussions.microsoft.com> wrote in message
news:C8C7BE9D-70BD-4BB3-BCA5-7D2ABFD4C3D2@.microsoft.com...
> Sorry, I'm not following you.
> Ok, using SQL Query Analyzer, I created my Select statement using the case
> statements instead of IIF's, and parsing completed successfully. It runs
> and
> selects the right information. Now what?
> Do I have to save this somewhere special? Then what.|||Hello
You can use a CASE expression instead of the IIF, using one of these
syntaxes:
CASE
WHEN condition
THEN result_if_true
ELSE result_if_false
END
or:
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
..
ELSE other_result
END
For more informations about CASE, see Books Online.
Razvan|||Use Query Analyzer(QA) to transfer ALL the old data from Access to SQL.
Copy it to tables - or better yet use DTS package to copy entire database.
If you are using a view to call the data for reports, use QA to test and
create a stored procedure with the test script. Call the stored procedure
from your reports.
If you want to use the QA script on occasion and not for any so-called
recurring reports, then save the script written in QA to any location (just
liek a text script) and open up the script when you want to run it and run i
t
at will.
"Holly" wrote:

> Thanks for the speedy response. Another question: If I create my view usin
g
> query analyzer, how do I save it as a query to link to Access?|||On Thu, 1 Jun 2006 11:26:01 -0700, Holly wrote:

>Sorry, I'm not following you.
>Ok, using SQL Query Analyzer, I created my Select statement using the case
>statements instead of IIF's, and parsing completed successfully. It runs an
d
>selects the right information. Now what?
>Do I have to save this somewhere special? Then what.
Hi Holly,
If you have a SELECT statement that returns the data you need, e.g.
SELECT au_fname FROM authors
than you can create a view by typing a CREATE VIEW statement before it
and executing the complete code:
CREATE VIEW Author_FirstNames
AS
SELECT au_fname FROM authors
Once this has executed successfullym you can use the Authro_FirstName
view just as you would use any regular table - and that includes
creating a linked table for it in Access.
Hugo Kornelis, SQL Server MVP

Convert Access Query to Transact SQL 2000 IIF to CASE

I need to convert a MS Access 2000 query into SQL Server 2000. Since
the IIF statements are not allowed in Transact-SQL, I 'm trying to
use the CASE Statement
I have two tables, Results and Sections. I need to import the section
records into the Results table. I tried to do a CASE statement, but so
far I cant' get the second IIF right.
In a nutshell, this is what this update query does:
Update the TotalScore in the tblResults table. If the tblResults.type
field is A, B, or C, then make it null. Otherwise, check if the
tblSections.MainScore1 field is null. If it is, then use the
tblResults.TotalScore value. If is not null, then use the
tblSections.MainScore1 value.
Here is the actual Access query syntax :
UPDATE [tblResults] INNER JOIN [tblSections] ON [tblResults].TestID =
[tblSections].TestID
SET [tblResults].TotalScore = IIf([Type]="A" Or [Type]="B" Or
[Type]="C",Null,
IIf(IsNull([tblSections].[MainScore1]),[tblResults].[TotalScore],[tblSections].[MainScore1]))
I have several other fields to update in this query, but they're very
similar to this one.
Any help would be appreciated it.
Thanks.let's see..
update tblResults
set TotalScore = case when r.type in ('A', 'B', 'C') then null else
coalesce(s.MainScore1, r.TotalScore) end
from tblResults r, tblSections s
where r.testID = s.testID
dean
<ILCSP@.NETZERO.NET> wrote in message
news:1145560609.392893.303600@.e56g2000cwe.googlegroups.com...
>I need to convert a MS Access 2000 query into SQL Server 2000. Since
> the IIF statements are not allowed in Transact-SQL, I 'm trying to
> use the CASE Statement
> I have two tables, Results and Sections. I need to import the section
> records into the Results table. I tried to do a CASE statement, but so
> far I cant' get the second IIF right.
> In a nutshell, this is what this update query does:
> Update the TotalScore in the tblResults table. If the tblResults.type
> field is A, B, or C, then make it null. Otherwise, check if the
> tblSections.MainScore1 field is null. If it is, then use the
> tblResults.TotalScore value. If is not null, then use the
> tblSections.MainScore1 value.
> Here is the actual Access query syntax :
> UPDATE [tblResults] INNER JOIN [tblSections] ON [tblResults].TestID =
> [tblSections].TestID
> SET [tblResults].TotalScore = IIf([Type]="A" Or [Type]="B" Or
> [Type]="C",Null,
> IIf(IsNull([tblSections].[MainScore1]),[tblResults].[TotalScore],[tblSections].[MainScore1]))
>
> I have several other fields to update in this query, but they're very
> similar to this one.
> Any help would be appreciated it.
> Thanks.
>|||--BEGIN PGP SIGNED MESSAGE--
Hash: SHA1
You can't use Access SQL syntax in SQL'r. Use Standard SQL syntax.:
UPDATE tblResults
SET TotalScore =
CASE WHEN [Type] IN ('A','B','C') THEN NULL
ELSE CASE WHEN MainScore1 IS NULL THEN TotalScore
ELSE (SELECT MainScore1 FROM tblSections
WHERE TestID = tblResults.TestID)
END
END
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)
--BEGIN PGP SIGNATURE--
Version: PGP for Personal Privacy 5.0
Charset: noconv
iQA/ AwUBREfx1oechKqOuFEgEQLAkgCfZlAFT1+TbFfW
cP+zDhv5c5hCnqgAnAji
grqbw9lVWW3Mm+3fC54YuPJj
=Rv7/
--END PGP SIGNATURE--
ILCSP@.NETZERO.NET wrote:
> I need to convert a MS Access 2000 query into SQL Server 2000. Since
> the IIF statements are not allowed in Transact-SQL, I 'm trying to
> use the CASE Statement
> I have two tables, Results and Sections. I need to import the section
> records into the Results table. I tried to do a CASE statement, but so
> far I cant' get the second IIF right.
> In a nutshell, this is what this update query does:
> Update the TotalScore in the tblResults table. If the tblResults.type
> field is A, B, or C, then make it null. Otherwise, check if the
> tblSections.MainScore1 field is null. If it is, then use the
> tblResults.TotalScore value. If is not null, then use the
> tblSections.MainScore1 value.
> Here is the actual Access query syntax :
> UPDATE [tblResults] INNER JOIN [tblSections] ON [tblResults].TestID =
> [tblSections].TestID
> SET [tblResults].TotalScore = IIf([Type]="A" Or [Type]="B" Or
> [Type]="C",Null,
> IIf(IsNull([tblSections].[MainScore1]),[tblResults].[TotalScore],[tblSections].[MainScore1]))
>
> I have several other fields to update in this query, but they're very
> similar to this one.|||Hello Guys, thanks for replying. I've been trying both suggestions and
both give me the same results. I'm able to get some of the total
scores, but not all of them.
I can get some of the total scores for not all of them. My guess is
that the error happens when the query is evaluating for null or perhaps
the declared join for the 2 tables is wrong.
the Table tblResults has 1 instance of TestID. The Table tblSections
has several instances of a TestID and they can have something in the
MainScore1 or be Null.
Here's an example of the tblSections table. In this example, I'm able
to get the 43 TotalScore for the 214371148 ID, but not for the other 2.
When running the old Access 2000 update query, I do get the 3
TotalScores.
Type TestID MainScore1
M 214209195 58
L 214371148 43
U 214217823 74
M 214209195
M 214209195
M 214209195
M 214209195
M 214209195
M 214209195
M 214209195
M 214209195
M 214209195
L 214371148
L 214371148
L 214371148
L 214371148
L 214371148
L 214371148
L 214371148
L 214371148
L 214371148
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823
U 214217823|||Hi,
Could you please post the DDL for the tables in question, INSERTs for the
sample data, and the expected results?
Thanks
Dean
<ILCSP@.NETZERO.NET> wrote in message
news:1145640771.510008.142980@.v46g2000cwv.googlegroups.com...
> Hello Guys, thanks for replying. I've been trying both suggestions and
> both give me the same results. I'm able to get some of the total
> scores, but not all of them.
> I can get some of the total scores for not all of them. My guess is
> that the error happens when the query is evaluating for null or perhaps
> the declared join for the 2 tables is wrong.
> the Table tblResults has 1 instance of TestID. The Table tblSections
> has several instances of a TestID and they can have something in the
> MainScore1 or be Null.
> Here's an example of the tblSections table. In this example, I'm able
> to get the 43 TotalScore for the 214371148 ID, but not for the other 2.
> When running the old Access 2000 update query, I do get the 3
> TotalScores.
> Type TestID MainScore1
> M 214209195 58
> L 214371148 43
> U 214217823 74
> M 214209195
> M 214209195
> M 214209195
> M 214209195
> M 214209195
> M 214209195
> M 214209195
> M 214209195
> M 214209195
> L 214371148
> L 214371148
> L 214371148
> L 214371148
> L 214371148
> L 214371148
> L 214371148
> L 214371148
> L 214371148
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
> U 214217823
>|||Here's the DDLs
CREATE TABLE [dbo].[tblResults] (
[InactivePrimary] [int] IDENTITY (1, 1) NOT NULL ,
[TestID] [int] NULL ,
[SSN] [varchar] (9) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[TestDate] [datetime] NULL ,
[TotalScore] [float] NULL ,
[MainScore1] [float] NULL ,
[MainStatus1] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[MainScore2] [float] NULL ,
[MainStatus2] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[MainScore3] [float] NULL ,
[MainStatus3] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[Sec1c] [float] NULL ,
[Sec1i] [float] NULL ,
[Sec2c] [float] NULL ,
[Sec2i] [float] NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[tblSections] (
[InactivePrimary] [int] IDENTITY (1, 1) NOT NULL ,
[TestID] [int] NULL ,
[MainScore1] [float] NULL ,
[MainScore2] [float] NULL ,
[MainScore3] [float] NULL ,
[MainStatus1] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[MainStatus2] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[MainStatus3] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[Sec1c] [float] NULL ,
[Sec1i] [float] NULL ,
[Sec2c] [float] NULL ,
[Sec2i] [float] NULL
) ON [PRIMARY]
GO
Since I already posted a short example of the tblSections table, here's
the one for the tblResults table
TestID SSN ExamType TotalScore
214209195 123456789 M
214371148 987654321 L
214398090 234567890 B
214398102 098765432 A
214217823 590380445 U
214430778 567890123 C
Based on the update query, I should get the totalscore for the records
with the TestID: 214209195, 214371148, and the 214217823. However, I
only get the results for the 214371148. The other 2 total scores are
still null.
Hope this helps.|||Hi,
Thanks for the DDL. And if you've posted the actual INSERT script, would it
look something like this?
insert tblResults (TestID, SSN, Type)
select
214209195, '123456789', 'M'
union all
select
214371148, '987654321', 'L'
union all
select
214398090, '234567890', 'B'
union all
select
214398102, '098765432', 'A'
union all
select
214217823, '590380445', 'U'
union all
select
214430778, '567890123', 'C'
insert tblSections (TestID, MainScore1)
select
214209195, 58
union all
select
214371148, 43
union all
select
214217823, 74
union all
select
214209195, null
union all
select
214209195, null
union all
select
214209195, null
union all
select
214209195, null
union all
select
214209195, null
union all
select
214209195, null
union all
select
214209195, null
union all
select
214209195, null
union all
select
214209195, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214371148, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
union all
select
214217823, null
If so, the update I posted yesterday should give the expected result. Once
again:
update tblResults
set TotalScore = case when r.type in ('A', 'B', 'C') then null else
coalesce(s.MainScore1, r.TotalScore) end
from tblResults r, tblSections s
where r.testID = s.testID
select TestId, TotalScore from tblResults
TestId TotalScore
-- ----
214209195 58.0
214371148 43.0
214398090 NULL
214398102 NULL
214217823 74.0
214430778 NULL
(6 row(s) affected)
Dean
<ILCSP@.NETZERO.NET> wrote in message
news:1145644726.162771.207080@.g10g2000cwb.googlegroups.com...
> Here's the DDLs
> CREATE TABLE [dbo].[tblResults] (
> [InactivePrimary] [int] IDENTITY (1, 1) NOT NULL ,
> [TestID] [int] NULL ,
> [SSN] [varchar] (9) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [TestDate] [datetime] NULL ,
> [TotalScore] [float] NULL ,
> [MainScore1] [float] NULL ,
> [MainStatus1] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [MainScore2] [float] NULL ,
> [MainStatus2] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [MainScore3] [float] NULL ,
> [MainStatus3] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [Sec1c] [float] NULL ,
> [Sec1i] [float] NULL ,
> [Sec2c] [float] NULL ,
> [Sec2i] [float] NULL
> ) ON [PRIMARY]
>
>
> CREATE TABLE [dbo].[tblSections] (
> [InactivePrimary] [int] IDENTITY (1, 1) NOT NULL ,
> [TestID] [int] NULL ,
> [MainScore1] [float] NULL ,
> [MainScore2] [float] NULL ,
> [MainScore3] [float] NULL ,
> [MainStatus1] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [MainStatus2] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [MainStatus3] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [Sec1c] [float] NULL ,
> [Sec1i] [float] NULL ,
> [Sec2c] [float] NULL ,
> [Sec2i] [float] NULL
> ) ON [PRIMARY]
> GO
>
> Since I already posted a short example of the tblSections table, here's
> the one for the tblResults table
> TestID SSN ExamType TotalScore
> 214209195 123456789 M
> 214371148 987654321 L
> 214398090 234567890 B
> 214398102 098765432 A
> 214217823 590380445 U
> 214430778 567890123 C
>
> Based on the update query, I should get the totalscore for the records
> with the TestID: 214209195, 214371148, and the 214217823. However, I
> only get the results for the 214371148. The other 2 total scores are
> still null.
> Hope this helps.
>

Convert Access query to SQL View

Hi,
I have used an access table to create a chart report to show how many calls
were handled in a month. How do i conver the Access sql to MS sql server
view. Here is the access sql:
SELECT (Format([ComplaintDate],"mmm"" '""yy")) AS Expr1, Count(*) AS [Count]
FROM [Complaints]
GROUP BY (Format([ComplaintDate],"mmm"" '""yy")),
(Year([ComplaintDate])*12+Month([Complai
ntDate])-1)
ORDER BY (Year([ComplaintDate])*12+Month([Complai
ntDate])-1);
In the MS Sql, the word FORMAT is not recognised. I have tried several ways
like this w/o any luck. Can anyone tell me the correct syntax for the above
sql querry.
Thanks
SenthilkumarCheck out CONVERT() in the BOL.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
.
"Senthilkumar" <kesk32@.yahoo.co.in> wrote in message
news:%234%232fJmJGHA.1388@.TK2MSFTNGP11.phx.gbl...
Hi,
I have used an access table to create a chart report to show how many calls
were handled in a month. How do i conver the Access sql to MS sql server
view. Here is the access sql:
SELECT (Format([ComplaintDate],"mmm"" '""yy")) AS Expr1, Count(*) AS [Count]
FROM [Complaints]
GROUP BY (Format([ComplaintDate],"mmm"" '""yy")),
(Year([ComplaintDate])*12+Month([Complai
ntDate])-1)
ORDER BY (Year([ComplaintDate])*12+Month([Complai
ntDate])-1);
In the MS Sql, the word FORMAT is not recognised. I have tried several ways
like this w/o any luck. Can anyone tell me the correct syntax for the above
sql querry.
Thanks
Senthilkumar|||To add to Tom's reply, you might want to consider leaving off the
formatting in the view and just return the raw data. Let the client
format the result set. Any time you format the data on the server, the
formatting functions you use have to operate on every single row, one
at a time.
--Mary
On Tue, 31 Jan 2006 18:09:30 +0530, "Senthilkumar"
<kesk32@.yahoo.co.in> wrote:

>Hi,
>I have used an access table to create a chart report to show how many calls
>were handled in a month. How do i conver the Access sql to MS sql server
>view. Here is the access sql:
>SELECT (Format([ComplaintDate],"mmm"" '""yy")) AS Expr1, Count(*) AS [Count]
>FROM [Complaints]
>GROUP BY (Format([ComplaintDate],"mmm"" '""yy")),
> (Year([ComplaintDate])*12+Month([Complai
ntDate])-1)
>ORDER BY (Year([ComplaintDate])*12+Month([Complai
ntDate])-1);
>In the MS Sql, the word FORMAT is not recognised. I have tried several ways
>like this w/o any luck. Can anyone tell me the correct syntax for the above
>sql querry.
>Thanks
>Senthilkumar
>

Convert Access Query to SQL Server View

SELECT DISTINCTROW "01C" AS dummy, Buildings.BuildingNumber,
UCASE(Buildings.BuildingName) AS BuildingName,
Buildings.MasterPlanCode, Buildings.UniformBuildingCode,
Buildings.FunctionalCategoryCode, Buildings.OwnershipCode,
Buildings.ConditionCode, Format$([BasicGrossArea],"0000000") AS
dBasicGrossArea, Format$([CoveredUnenclosedGrossArea],"0000000") AS
dCoveredUnenclosedGrossArea,
IIf(Month([DateOccupancy])>9,Month([DateOccupancy]),"0" &
Month([DateOccupancy])) & Year([DateOccupancy]) AS dDateOccupancy,
Buildings.YearConstructed, Format$([NumberLevels],"00") AS
dNumberLevels, Format$([UnrelatedGrossArea],"0000000") AS
dUnrelatedGrossArea, Buildings.YearLatestImprovement,
UCASE(Buildings.Address) AS Address, Buildings.CityCode,
CityCodes.CountyCode, Format$([Circulation],"0000000") AS dCirculation,
Format$([PublicToiletArea],"0000000") AS dPublicToiletArea,
Format$([Mechanical],"0000000") AS dMechanical,
Format$([Custodial],"0000000") AS dCustodial
FROM CityCodes INNER JOIN Buildings ON CityCodes.CityCode =
Buildings.CityCode
ORDER BY "01C", Buildings.BuildingNumber, Buildings.BuildingName;

Please if anyone can help me in Converting the above given Access Query
to Sql Server. I don't know which function to use for format$, IIF. I
would really appreciate your suggestions.

Thanks,On 17 May 2006 10:02:37 -0700, s_wadhwa@.berkeley.edu wrote:

>SELECT DISTINCTROW "01C" AS dummy, Buildings.BuildingNumber,
>UCASE(Buildings.BuildingName) AS BuildingName,
>Buildings.MasterPlanCode, Buildings.UniformBuildingCode,
>Buildings.FunctionalCategoryCode, Buildings.OwnershipCode,
>Buildings.ConditionCode, Format$([BasicGrossArea],"0000000") AS
>dBasicGrossArea, Format$([CoveredUnenclosedGrossArea],"0000000") AS
>dCoveredUnenclosedGrossArea,
>IIf(Month([DateOccupancy])>9,Month([DateOccupancy]),"0" &
>Month([DateOccupancy])) & Year([DateOccupancy]) AS dDateOccupancy,
>Buildings.YearConstructed, Format$([NumberLevels],"00") AS
>dNumberLevels, Format$([UnrelatedGrossArea],"0000000") AS
>dUnrelatedGrossArea, Buildings.YearLatestImprovement,
>UCASE(Buildings.Address) AS Address, Buildings.CityCode,
>CityCodes.CountyCode, Format$([Circulation],"0000000") AS dCirculation,
>Format$([PublicToiletArea],"0000000") AS dPublicToiletArea,
>Format$([Mechanical],"0000000") AS dMechanical,
>Format$([Custodial],"0000000") AS dCustodial
>FROM CityCodes INNER JOIN Buildings ON CityCodes.CityCode =
>Buildings.CityCode
>ORDER BY "01C", Buildings.BuildingNumber, Buildings.BuildingName;
>
>Please if anyone can help me in Converting the above given Access Query
>to Sql Server. I don't know which function to use for format$, IIF. I
>would really appreciate your suggestions.
>Thanks,

Hi s_wadhwa,

Change doouble quotes to single quotes.

Use + instead of & for string concatenation.

Replace UCASE() with UPPER()

Replace IIf with CASE (look it up in Books Online)

My knowledge of Format$() is very llimited, but if (for isntance) the
function Format$([Custodial],"0000000") is intended to format Custodial
as a 7-digit numeric string with leading zerooes (e.g. 0001234), then
you can replace it with:
RIGHT (REPLICATE('0', 7) + STR(Custodial), 7)

Finally, remove the constant from the ORDER BY list. It serves no
purpose.

--
Hugo Kornelis, SQL Server MVP|||Hi Hugo,
Thanks a lot for your quick response. the suggestions were really
helpful. Is there any book to refer or some online material to refer
to. I have lots of other doubts regarding converting Access queries to
SQL.

Thanks,
Shalini|||Hi,

If anyone has done the conversion of parameterized query in Access to
SQL Server. Please guide me how to solve this query and how to take
input in SQL query from Access forms.

PARAMETERS [[forms]!frmRooms![BuildingNumber]] Text ( 255 ),
[[forms]!frmRooms![ctlFloor]] Text ( 255 ),
[[forms]!frmRooms![DepartmentFilter]] Text ( 255 );
SELECT *
FROM Rooms
WHERE (((Rooms.BuildingNumber)=[forms]![frmRooms]![BuildingNumber]) AND
((Rooms.Floor) Like [forms]![frmRooms]![ctlFloor]) AND
((Rooms.DepartmentCode) Like
Mid$([forms]![frmRooms]![DepartmentFilter],1,4)) AND
((Rooms.RoomUseCode) Like [forms]![frmRooms]![RmCdFilter]))
ORDER BY Rooms.BuildingNumber, Rooms.RoomNumber;

thanks in advance for your help.
Shalini|||On 18 May 2006 12:59:23 -0700, s_wadhwa@.berkeley.edu wrote:

>Hi,
>If anyone has done the conversion of parameterized query in Access to
>SQL Server. Please guide me how to solve this query and how to take
>input in SQL query from Access forms.

Hi Shalini,

I see that your parameters refer to forms. Keep in mind that SQL Server
is not aware of the forms in yoour front-end - a big difference from
Access, which is DB and front-end lumped together in one application.

One possible way to convert this to SQL Server would be to create a
stored procedure:

CREATE PROC GoodNameGoesHere
(@.BuildingNumber varchar(255),
@.ctlFloor varchar(255),
@.DepartmentFilter varchar(255))
AS
SELECT Col1, Col2, Col3, ...-- Never use SELECT * in production code
FROM Rooms
WHERE BuildingNumber = @.BuildingNumber
AND "Floor" LIKE @.ctlFloor
AND DepartmentCode LIKE SUBSTRING(@.DepartmentFilter, 1, 4)
ORDER BY BuildingNumber, RoomNumber;

BTW, using a char datatype for a column named "Number" is highly
suspicious to me...

--
Hugo Kornelis, SQL Server MVP|||Hi there,

I have an Access query that I've been trying to convert to SQL Server
view and although I've converted most of the syntax from access to sql
I still can't make it work. I'm getting errors within GROUP BY and
HAVING clauses. Anyone has an idea? Thanks...

SELECT DateName(qq,GetDate()) + '/' + DateName(yy,GetDate()) AS Expr1,
GetDate()-O_DateOfAddress AS Expr3,
DateName(qq,O_DateofAddress) + '/' + DateName(yy,O_DateofAddress) AS
Expr2,
qry_offender_master.O_VerificationQuarter,
qry_offender_master.O_Probation,
qry_offender_master.O_active_case, qry_offender_master.O_OutOfCounty,
qry_offender_master.O_deceased, qry_offender_master.O_Sex_Probation,
qry_offender_master.O_DateofAddress, qry_offender_master.O_Doc,
qry_offender_master.O_LastName, qry_offender_master.O_FirstName,
qry_offender_master.O_MiddleName, qry_offender_master.O_Address,
qry_offender_master.O_CityEntry, qry_offender_master.O_State,
qry_offender_master.O_Zip, qry_offender_master.O_Sector,
tbl_state.State,
qry_offender_master.Ca_WarrantIssued,
qry_offender_master.O_DateofBirth,
qry_offender_master.O_Absconder
FROM qry_offender_master LEFT JOIN tbl_state ON
qry_offender_master.O_State = tbl_state.State
GROUP BY DateName(qq,GetDate()) + '/' + DateName(yy,GetDate()),
GetDate()-O_DateOfAddress,
DateName(qq,O_DateofAddress) + '/' + DateName(yy,O_DateofAddress),
qry_offender_master.O_VerificationQuarter,
qry_offender_master.O_Probation,
qry_offender_master.O_active_case, qry_offender_master.O_OutOfCounty,
qry_offender_master.O_deceased, qry_offender_master.O_Sex_Probation,
qry_offender_master.O_DateofAddress, qry_offender_master.O_Doc,
qry_offender_master.O_LastName, qry_offender_master.O_FirstName,
qry_offender_master.O_MiddleName, qry_offender_master.O_Address,
qry_offender_master.O_CityEntry, qry_offender_master.O_State,
qry_offender_master.O_Zip, qry_offender_master.O_Sector,
tbl_state.State,
qry_offender_master.Ca_WarrantIssued,
qry_offender_master.O_DateofBirth,
qry_offender_master.O_Absconder
HAVING (((DateName(qq,O_DateofAddress) + '/' +
DateName(yy,O_DateofAddress)) <> DateName(qq,GetDate()) + '/' +
DateName(yy,GetDate())) AND
((qry_offender_master.O_VerificationQuarter)= DateName(qq,GetDate()))
AND ((qry_offender_master.O_Probation)=0) AND
((qry_offender_master.O_OutOfCounty)=0) AND
((qry_offender_master.O_deceased)=0) AND
((qry_offender_master.O_Sex_Probation)=0) AND
((qry_offender_master.O_Absconder)=0)) OR
(((DateName(qq,O_DateofAddress) + '/' + DateName(yy,O_DateofAddress))<>
DateName(qq,GetDate()) + '/' + DateName(yy,GetDate())) AND
((qry_offender_master.O_VerificationQuarter)= DateName(qq,GetDate()))
AND ((qry_offender_master.O_Probation)=0) AND
((qry_offender_master.O_OutOfCounty)=0) AND
((qry_offender_master.O_deceased)=0) AND
((qry_offender_master.O_Sex_Probation)=0) AND
((qry_offender_master.O_DateofAddress) Is Null) AND
((qry_offender_master.O_Absconder)=0))
ORDER BY qry_offender_master.O_LastName

Hugo Kornelis wrote:
> On 18 May 2006 12:59:23 -0700, s_wadhwa@.berkeley.edu wrote:
> >Hi,
> >If anyone has done the conversion of parameterized query in Access to
> >SQL Server. Please guide me how to solve this query and how to take
> >input in SQL query from Access forms.
> Hi Shalini,
> I see that your parameters refer to forms. Keep in mind that SQL Server
> is not aware of the forms in yoour front-end - a big difference from
> Access, which is DB and front-end lumped together in one application.
> One possible way to convert this to SQL Server would be to create a
> stored procedure:
> CREATE PROC GoodNameGoesHere
> (@.BuildingNumber varchar(255),
> @.ctlFloor varchar(255),
> @.DepartmentFilter varchar(255))
> AS
> SELECT Col1, Col2, Col3, ...-- Never use SELECT * in production code
> FROM Rooms
> WHERE BuildingNumber = @.BuildingNumber
> AND "Floor" LIKE @.ctlFloor
> AND DepartmentCode LIKE SUBSTRING(@.DepartmentFilter, 1, 4)
> ORDER BY BuildingNumber, RoomNumber;
> BTW, using a char datatype for a column named "Number" is highly
> suspicious to me...
> --
> Hugo Kornelis, SQL Server MVP|||Ok, I've changed "GetDate()-O_DateOfAddress" to DateDiff(day,
O_DateOfAddress, GetDate()) and the only thing left has to do with
group by clause. So, is there any way I can use expressions (Expr1,
Expr2...) in GROUP By clause because obviously this is possible in
access but not in sql server...I tried both putting "Group by Expr1,
Expr2" and "Group by DateName(qq,GetDate()) + '/' +
DateName(yy,GetDate()) AS Expr1, GetDate()-O_DateOfAddress AS Expr3..."
but no success? Thanks in advance...|||thanks for guidance.
i resolved that issue.

shalini|||On 23 May 2006 05:51:47 -0700, lakimaki wrote:

>Hi there,
>I have an Access query that I've been trying to convert to SQL Server
>view and although I've converted most of the syntax from access to sql
>I still can't make it work. I'm getting errors within GROUP BY and
>HAVING clauses. Anyone has an idea? Thanks...
(snip)

Hi lakimaki,

There are several things in yoour query that I don't understand.

1. Why are you joining in the tblState table? Unless I am missing
something, you only use it to display the tblState.State column, which
is also the joining column. Why not display O_State and remove the join
to tblState?

2. Why do you need the GROUP BY clause? Since you include all columns in
the WHERE clause and since there are no aggregates used anywhere, this
is the same as just using DISTINCT to remove duplicates - and if your
table is well designed, there shouldn't be any duplicates. Just remove
the entire GROUP BY and change HAVING to WHERE.

3. The HAVING part looks strange too. It consists of two parts, combined
with OR. But the second part is an exact copy of the first part, with
only one extra requirement added. And that extra requirement has the
result that this second part can NEVER be true - since DateOfAddress can
never be both NULL and in the current quarter.

4. The test that DateOfAddress is in the current quarter is not done in
the most efficient way. Instead of using an expression to extract
quarter and year from this column, you shoould compare this column to
the start of the current and the next quarter - that way, an index on
DateOfAddress (if any exists) can be used to quickly narrow down the
amount of rows to process.

As far as I see, you could rewrite your query to:

SELECT DATENAME(qq, CURRENT_TIMESTAMP) + '/'
+ DATENAME(yy, CURRENT_TIMESTAMP) AS Expr1,
DATEDIFF(day, O_DateOfAddress, CURRENT_TIMESTAMP) AS Expr3,
DATENAME(qq, O_DateofAddress) + '/'
+ DATENAME(yy, O_DateofAddress) AS Expr2,
O_VerificationQuarter,
O_Probation,
O_active_case,
O_OutOfCounty,
O_deceased,
O_Sex_Probation,
O_DateofAddress,
O_Doc,
O_LastName,
O_FirstName,
O_MiddleName,
O_Address,
O_CityEntry,
O_State,
O_Zip,
O_Sector,
O_State,
Ca_WarrantIssued,
O_DateofBirth,
O_Absconder
FROM qry_offender_master
WHERE O_DateOfAddress >= DATEADD(qq,
DATEDIFF(qq, '20000101',
CURRENT_TIMESTAMP),
'20000101')
AND O_DateOfAddress < DATEADD(qq,
DATEDIFF(qq, '20000101',
CURRENT_TIMESTAMP),
'20000401')
AND O_VerificationQuarter = DATENAME(qq, CURRENT_TIMESTAMP)
AND O_Probation = 0
AND O_OutOfCounty = 0
AND O_deceased = 0
AND O_Sex_Probation = 0
AND O_Absconder = 0
ORDER BY O_LastName

(Untested - see www.aspfaq.com.5006 if you prefer a tested reply)

>SELECT DateName(qq,GetDate()) + '/' + DateName(yy,GetDate()) AS Expr1,
>GetDate()-O_DateOfAddress AS Expr3,
>DateName(qq,O_DateofAddress) + '/' + DateName(yy,O_DateofAddress) AS
>Expr2,
>qry_offender_master.O_VerificationQuarter,
>qry_offender_master.O_Probation,
>qry_offender_master.O_active_case, qry_offender_master.O_OutOfCounty,
>qry_offender_master.O_deceased, qry_offender_master.O_Sex_Probation,
>qry_offender_master.O_DateofAddress, qry_offender_master.O_Doc,
>qry_offender_master.O_LastName, qry_offender_master.O_FirstName,
>qry_offender_master.O_MiddleName, qry_offender_master.O_Address,
>qry_offender_master.O_CityEntry, qry_offender_master.O_State,
>qry_offender_master.O_Zip, qry_offender_master.O_Sector,
>tbl_state.State,
>qry_offender_master.Ca_WarrantIssued,
>qry_offender_master.O_DateofBirth,
>qry_offender_master.O_Absconder
>FROM qry_offender_master LEFT JOIN tbl_state ON
>qry_offender_master.O_State = tbl_state.State
>GROUP BY DateName(qq,GetDate()) + '/' + DateName(yy,GetDate()),
>GetDate()-O_DateOfAddress,
>DateName(qq,O_DateofAddress) + '/' + DateName(yy,O_DateofAddress),
>qry_offender_master.O_VerificationQuarter,
>qry_offender_master.O_Probation,
>qry_offender_master.O_active_case, qry_offender_master.O_OutOfCounty,
>qry_offender_master.O_deceased, qry_offender_master.O_Sex_Probation,
>qry_offender_master.O_DateofAddress, qry_offender_master.O_Doc,
>qry_offender_master.O_LastName, qry_offender_master.O_FirstName,
>qry_offender_master.O_MiddleName, qry_offender_master.O_Address,
>qry_offender_master.O_CityEntry, qry_offender_master.O_State,
>qry_offender_master.O_Zip, qry_offender_master.O_Sector,
>tbl_state.State,
>qry_offender_master.Ca_WarrantIssued,
>qry_offender_master.O_DateofBirth,
>qry_offender_master.O_Absconder
>HAVING (((DateName(qq,O_DateofAddress) + '/' +
>DateName(yy,O_DateofAddress)) <> DateName(qq,GetDate()) + '/' +
>DateName(yy,GetDate())) AND
>((qry_offender_master.O_VerificationQuarter)= DateName(qq,GetDate()))
>AND ((qry_offender_master.O_Probation)=0) AND
>((qry_offender_master.O_OutOfCounty)=0) AND
>((qry_offender_master.O_deceased)=0) AND
>((qry_offender_master.O_Sex_Probation)=0) AND
>((qry_offender_master.O_Absconder)=0)) OR
>(((DateName(qq,O_DateofAddress) + '/' + DateName(yy,O_DateofAddress))<>
>DateName(qq,GetDate()) + '/' + DateName(yy,GetDate())) AND
>((qry_offender_master.O_VerificationQuarter)= DateName(qq,GetDate()))
>AND ((qry_offender_master.O_Probation)=0) AND
>((qry_offender_master.O_OutOfCounty)=0) AND
>((qry_offender_master.O_deceased)=0) AND
>((qry_offender_master.O_Sex_Probation)=0) AND
>((qry_offender_master.O_DateofAddress) Is Null) AND
>((qry_offender_master.O_Absconder)=0))
>ORDER BY qry_offender_master.O_LastName
>
>Hugo Kornelis wrote:
>> On 18 May 2006 12:59:23 -0700, s_wadhwa@.berkeley.edu wrote:
>>
>> >Hi,
>>> >If anyone has done the conversion of parameterized query in Access to
>> >SQL Server. Please guide me how to solve this query and how to take
>> >input in SQL query from Access forms.
>>
>> Hi Shalini,
>>
>> I see that your parameters refer to forms. Keep in mind that SQL Server
>> is not aware of the forms in yoour front-end - a big difference from
>> Access, which is DB and front-end lumped together in one application.
>>
>> One possible way to convert this to SQL Server would be to create a
>> stored procedure:
>>
>> CREATE PROC GoodNameGoesHere
>> (@.BuildingNumber varchar(255),
>> @.ctlFloor varchar(255),
>> @.DepartmentFilter varchar(255))
>> AS
>> SELECT Col1, Col2, Col3, ...-- Never use SELECT * in production code
>> FROM Rooms
>> WHERE BuildingNumber = @.BuildingNumber
>> AND "Floor" LIKE @.ctlFloor
>> AND DepartmentCode LIKE SUBSTRING(@.DepartmentFilter, 1, 4)
>> ORDER BY BuildingNumber, RoomNumber;
>>
>> BTW, using a char datatype for a column named "Number" is highly
>> suspicious to me...
>>
>> --
>> Hugo Kornelis, SQL Server MVP

--
Hugo Kornelis, SQL Server MVP

Convert Access query to sql

how to convert this access query to sql query

IIf([Total Bunches] > 0, Production * 1000 / [Total Bunches], 0) as Name2

SUM(IIf(BlockInYield = -1, [SIZE], 0)) as Name1

IIf(BlockInYield = TRUE, IIf(TC_M > 0, TC_M, TC_DENS *[SIZE]), 0) as Name

please......

case

when [Total Bunches] > 0 then Production * 1000 / [Total Bunches]

else 0

end

as Name2,

SUM(

case

when BlockInYield = -1 then [SIZE]

else 0

end

)

as Name1,

case when BlockInYield = 1 then (case when TC_M > 0 then TC_M else TC_DENS *[SIZE] end)

else 0

end

as Name

Thanks

Naras

|||There is no IFF operator in TSQL; as Naras is indicating the way to approach converting an IFF statement is to use an abstraction using CASE statements.sqlsql

Convert Access CROSSTAB query to SQL Table or View

I have a Crosstab query that I need to convert to SQL to complete upsize of a large DB.
I have a table (here referred to as Data) with the fields: Resource, Date and Count. I need to transform it to a table (or view) with a fields called Date, and one field for each Resource that exists in the Data table.

The Data table looks like this:
RES DATE COUNT
res1 Jan06 5
res2 Jan06 4
res3 Jan 06 2
res1 Feb06 9
res2 Feb06 5
res3 Feb06 7

etc

The Access crosstab query sql is:
=====================
TRANSFORM Sum(Data.Count) AS SumOfCount
SELECT Data.Date
FROM Data
GROUP BY Data.Date
ORDER BY Data.Date
PIVOT Data.Resource;

which gives the resultant data set for charting:
Date res1 res2 res3
Jan06 5 4 2
Feb06 9 5 7

TRANSFORM is not T-SQL. I assume I need a usp to create the required table. Any ideas please?

George Cooper.

In SQL Server, you can use either CASE statement to pivot the table or PIVOT function in SQL Server 2005.

Here is CASE solution:

SELECT sDate,
AVG(CASE WHEN res ='res1' THEN sCount END) as res1,
AVG(CASE WHEN res ='res2' THEN sCount END) as res2,
AVG(CASE WHEN res ='res3' THEN sCount END) as res3
FROM (SELECT sDate, res, sCount FROM myDATA) p
WHERE res IN ('res1', 'res2', 'res3')
GROUP BY sDate
ORDER By Convert(DATETIME,'01'+sDate,13)

PIVOT solution:(SQL Server 2005)

SELECT sDate, res1, res2, res3
FROM (SELECT sDate, res, sCount FROM myDATA) p
PIVOT (AVG(sCount) FOR res IN ([res1], [res2], [res3])) AS pvt
ORDER By Convert(DATETIME,'01'+sDate,13)

You need to pay attention to your so-called Date column. I convert the text (nvarchar) field to datetime for sorting purpose.

|||

Thanks,

Pivot soultion works well.

Regards\

George Cooper

|||There is an interesting article on this issue at:
http://tinyurl.com/mgrwo

|||

But if the number of destination columns (res1, res2, res3,...,resN) is unknown?

Using SqlServer 2000.

Later i found these great article:
http://www.sqlservercentral.com/columnists/plarsson/pivottableformicrosoftsqlserver.asp

Convert Access CROSSTAB query to SQL Table or View

I have a Crosstab query that I need to convert to SQL to complete upsize of a large DB.
I have a table (here referred to as Data) with the fields: Resource, Date and Count. I need to transform it to a table (or view) with a fields called Date, and one field for each Resource that exists in the Data table.

The Data table looks like this:
RES DATE COUNT
res1 Jan06 5
res2 Jan06 4
res3 Jan 06 2
res1 Feb06 9
res2 Feb06 5
res3 Feb06 7

etc

The Access crosstab query sql is:
=====================
TRANSFORM Sum(Data.Count) AS SumOfCount
SELECT Data.Date
FROM Data
GROUP BY Data.Date
ORDER BY Data.Date
PIVOT Data.Resource;

which gives the resultant data set for charting:
Date res1 res2 res3
Jan06 5 4 2
Feb06 9 5 7

TRANSFORM is not T-SQL. I assume I need a usp to create the required table. Any ideas please?

George Cooper.

In SQL Server, you can use either CASE statement to pivot the table or PIVOT function in SQL Server 2005.

Here is CASE solution:

SELECT sDate,
AVG(CASE WHEN res ='res1' THEN sCount END) as res1,
AVG(CASE WHEN res ='res2' THEN sCount END) as res2,
AVG(CASE WHEN res ='res3' THEN sCount END) as res3
FROM (SELECT sDate, res, sCount FROM myDATA) p
WHERE res IN ('res1', 'res2', 'res3')
GROUP BY sDate
ORDER By Convert(DATETIME,'01'+sDate,13)

PIVOT solution:(SQL Server 2005)

SELECT sDate, res1, res2, res3
FROM (SELECT sDate, res, sCount FROM myDATA) p
PIVOT (AVG(sCount) FOR res IN ([res1], [res2], [res3])) AS pvt
ORDER By Convert(DATETIME,'01'+sDate,13)

You need to pay attention to your so-called Date column. I convert the text (nvarchar) field to datetime for sorting purpose.

|||

Thanks,

Pivot soultion works well.

Regards\

George Cooper

|||There is an interesting article on this issue at:
http://tinyurl.com/mgrwo

|||

But if the number of destination columns (res1, res2, res3,...,resN) is unknown?

Using SqlServer 2000.

Later i found these great article:
http://www.sqlservercentral.com/columnists/plarsson/pivottableformicrosoftsqlserver.asp

Convert Access CROSSTAB query to SQL Table or View

TRANSFORM IIf(Sum(IIf([blockinyield]=True,[SIZE],0))>0,Sum([Y_TOTAL_ton])/Sum(IIf([blockinyield]=True,[SIZE],0)),0) AS Yield_THA
SELECT OILPALM.NAME, OILPALM.YEAR, formatyear([year]) AS yearDisplay, Count(OILPALM.BLOCK) AS CountOfBLOCK
FROM OILPALM
GROUP BY OILPALM.NAME, OILPALM.YEAR
PIVOT Year([D_PLANTED]);

how to convert the access query above to sql server 2000

In SQL Server 2000 you have't have predefined operator to get the PIVOT table..

Here you have to manually write the query to get the pivot result...

(Example)

Code Snippet

Create Table #BikeSales
(
Year int,
Product Varchar(100),
Sales Int
)

Insert Into #BikeSales Values ('2005', 'HONDA F1', 10000)
Insert Into #BikeSales Values ('2006', 'HONDA F1', 6000)
Insert Into #BikeSales Values ('2007', 'HONDA F1', 7000)

Insert Into #BikeSales Values ('2005', 'HONDA IRL', 100)
Insert Into #BikeSales Values ('2006', 'HONDA IRL', 99)
Insert Into #BikeSales Values ('2007', 'HONDA IRL', 1000)

Insert Into #BikeSales Values ('2005', 'HONDA MotoGP', 124)
Insert Into #BikeSales Values ('2006', 'HONDA MotoGP', 344)
Insert Into #BikeSales Values ('2007', 'HONDA MotoGP', 132)

Insert Into #BikeSales Values ('2005', 'HONDA Super GT', 234)
Insert Into #BikeSales Values ('2006', 'HONDA Super GT', 32344)
Insert Into #BikeSales Values ('2007', 'HONDA Super GT', 123232)

Select
[Main].Product
,Sum([2005].Sales) as [2005]
,Sum([2006].Sales) as [2006]
,Sum([2007].Sales) as [2007]
From (Select Distinct Product From #BikeSales) as [Main]
Left Outer Join (Select * From #BikeSales Where Year=2005) as [2005] On [2005].Product=[Main].Product
Left Outer Join (Select * From #BikeSales Where Year=2006) as [2006] On [2006].Product=[Main].Product
Left Outer Join (Select * From #BikeSales Where Year=2007) as [2007] On [2007].Product=[Main].Product
Group By [Main].Product

You can generate the above query dynamically using the following script..

Code Snippet

Declare @.JoinQuery as Varchar(1000);
Declare @.SelectQuery as Varchar(1000);
Declare @.PreparedJoinQuery as Varchar(1000);
Declare @.PreparedSelectQuery as Varchar(1000);
Select @.JoinQuery = '', @.SelectQuery = ''
Select @.PreparedJoinQuery = 'Left Outer Join (Select * From #BikeSales Where Year=?) as [?] On [?].Product=[Main].Product '
Select @.PreparedSelectQuery =',Sum([?].Sales) as [?]'
Select
@.JoinQuery = @.JoinQuery + Replace(@.PreparedJoinQuery,'?',Cast(year as Varchar))
,@.SelectQuery = @.SelectQuery + Replace(@.PreparedSelectQuery,'?',Cast(year as Varchar)) From #BikeSales Group By Year

Exec ('Select [Main].Product' + @.SelectQuery + ' From (Select Distinct Product From #BikeSales) as [Main]' + @.JoinQuery + ' Group By [Main].Product')

|||

Using Manivannan's data, this method of creating a 'pivot' table in SQL 2005 is quite a bit more efficient. (Single Pass, No JOINS, NO Sub-Queries, No Dynamic SQL.)

Code Snippet


DECLARE @.BikeSales table
( [Year] int,
Product varchar(25),
Sales int
)


Insert Into @.BikeSales Values ('2005', 'HONDA F1', 10000)
Insert Into @.BikeSales Values ('2006', 'HONDA F1', 6000)
Insert Into @.BikeSales Values ('2007', 'HONDA F1', 7000)
Insert Into @.BikeSales Values ('2005', 'HONDA IRL', 100)
Insert Into @.BikeSales Values ('2006', 'HONDA IRL', 99)
Insert Into @.BikeSales Values ('2007', 'HONDA IRL', 1000)
Insert Into @.BikeSales Values ('2005', 'HONDA MotoGP', 124)
Insert Into @.BikeSales Values ('2006', 'HONDA MotoGP', 344)
Insert Into @.BikeSales Values ('2007', 'HONDA MotoGP', 132)
Insert Into @.BikeSales Values ('2005', 'HONDA Super GT', 234)
Insert Into @.BikeSales Values ('2006', 'HONDA Super GT', 32344)
Insert Into @.BikeSales Values ('2007', 'HONDA Super GT', 123232)


Select
Product,
[2005] = sum( CASE [Year] WHEN 2005 THEN Sales END ),
[2006] = sum( CASE [Year] WHEN 2006 THEN Sales END ),
[2007] = sum( CASE [Year] WHEN 2007 THEN Sales END )
FROM @.BikeSales
GROUP BY Product
ORDER BY Product

Convert Access CROSSTAB query to SQL Table or View

I have a Crosstab query that I need to convert to SQL to complete upsize of a large DB.
I have a table (here referred to as Data) with the fields: Resource, Date and Count. I need to transform it to a table (or view) with a fields called Date, and one field for each Resource that exists in the Data table.

The Data table looks like this:
RES DATE COUNT
res1 Jan06 5
res2 Jan06 4
res3 Jan 06 2
res1 Feb06 9
res2 Feb06 5
res3 Feb06 7

etc

The Access crosstab query sql is:
=====================
TRANSFORM Sum(Data.Count) AS SumOfCount
SELECT Data.Date
FROM Data
GROUP BY Data.Date
ORDER BY Data.Date
PIVOT Data.Resource;

which gives the resultant data set for charting:
Date res1 res2 res3
Jan06 5 4 2
Feb06 9 5 7

TRANSFORM is not T-SQL. I assume I need a usp to create the required table. Any ideas please?

George Cooper.

In SQL Server, you can use either CASE statement to pivot the table or PIVOT function in SQL Server 2005.

Here is CASE solution:

SELECT sDate,
AVG(CASE WHEN res ='res1' THEN sCount END) as res1,
AVG(CASE WHEN res ='res2' THEN sCount END) as res2,
AVG(CASE WHEN res ='res3' THEN sCount END) as res3
FROM (SELECT sDate, res, sCount FROM myDATA) p
WHERE res IN ('res1', 'res2', 'res3')
GROUP BY sDate
ORDER By Convert(DATETIME,'01'+sDate,13)

PIVOT solution:(SQL Server 2005)

SELECT sDate, res1, res2, res3
FROM (SELECT sDate, res, sCount FROM myDATA) p
PIVOT (AVG(sCount) FOR res IN ([res1], [res2], [res3])) AS pvt
ORDER By Convert(DATETIME,'01'+sDate,13)

You need to pay attention to your so-called Date column. I convert the text (nvarchar) field to datetime for sorting purpose.

|||

Thanks,

Pivot soultion works well.

Regards\

George Cooper

|||There is an interesting article on this issue at:
http://tinyurl.com/mgrwo

|||

But if the number of destination columns (res1, res2, res3,...,resN) is unknown?

Using SqlServer 2000.

Later i found these great article:
http://www.sqlservercentral.com/columnists/plarsson/pivottableformicrosoftsqlserver.asp

Convert a time field in the select statement of the query

Hi,

I have a field called "Starting DateTime" and I want to convert into my local time. I can convert it in the report with the expression "=System.TimeZone.CurrentTimeZone.ToLocalTime(Fields!Starting_DateTime.Value)", but that is too late. I want to convert it in the Select statement of the query.

Can anyone help me please?

Thx

I'm not entirely sure what you're trying to get at, but SQL Server has the following function that will get you the current UTC time:

GETUTCDATE()

If you are trying to convert the time from the timestamp to the corresponding local timestamp value, you would need to know the offset and add this time to the existing field.

Hope this helps some.

Simone

|||

Yeah!! That's the solution...... 2 weeks of deep frustrations and just such a simple solution..... wow!

Thx a lot!!! SmileSmile

|||

No problem, glad it worked for you. If you mark this as the answer it will better help others. Thanks.

Simone

sqlsql

Tuesday, March 27, 2012

Convert

I am using the following snippet of code to help me convert the date and tim
e
in a query I am writing.
SELECT dbo.Users.FirstName + ' ' + dbo.Users.LastName AS Student,
dbo.Subjects.Subject, Convert
(Char(15),dbo.TrainingSchedules.RequestedDate,101) AS Date,
Convert
(Char(8),dbo.TrainingSchedules.RequestedTime,108) AS Time,
The date converts fine to the format that I need. The time does not. It is
being displayed as military times and I want it to appear as a standard 12
format. i.e 9:00 AM
I tried all of the codes I found in BOL and none gave me what I wanted. Is
it possible to do what I want to do?
ThanksI think you can use the following:
Convert
(Char(8),dbo.TrainingSchedules.RequestedTime,100) AS Time,
HTH
Barry|||Thanks. But it still shows up as military time when I use 100.
"Barry" wrote:

> I think you can use the following:
> Convert
> (Char(8),dbo.TrainingSchedules.RequestedTime,100) AS Time,
> HTH
> Barry
>|||Umm not sure why - I have just checked the BOL and it confirms my
suggestion in the CAST and CONVERT section.
What are storing the Time as? Datetime?
Barry|||right(convert(varchar,dbo.TrainingSchedule.RequestedTime,100),7) as Time
Brennan wrote:

>I am using the following snippet of code to help me convert the date and ti
me
>in a query I am writing.
>SELECT dbo.Users.FirstName + ' ' + dbo.Users.LastName AS Student,
>dbo.Subjects.Subject, Convert
>(Char(15),dbo.TrainingSchedules.RequestedDate,101) AS Date,
> Convert
>(Char(8),dbo.TrainingSchedules.RequestedTime,108) AS Time,
>The date converts fine to the format that I need. The time does not. It i
s
>being displayed as military times and I want it to appear as a standard 12
>format. i.e 9:00 AM
>I tried all of the codes I found in BOL and none gave me what I wanted. Is
>it possible to do what I want to do?
>Thanks
>|||Usually, formatting is best left to the client since most client languages
have far better capabilities in this area. It isn't particularly clear what
datatypes you are using for the columns in question - the assumption is that
they are both datetime (or smalldatetime). If this assumption is not valid,
then you should clarify what the datatypes are and the expected formats of
the data (if applicable). One can question the wisdom of separating these
two intimately related bits of information into two separate columns -
especially given the dbms support.
If you must persist in this quest, you will most likely need to "generate"
the appropriate information in some convoluted and complex expression (and
possibly multiple queries). For the convert function, none of the available
formats has a space between the time and the AM/PM characters. If this can
be ignored, the 100 format is the closest - convert to this format and take
the last 7 characters (or all the characters from the last space to the end
of the string). You could also use the datepart functions to strip off and
convert the bits that are of interest. Experiment a bit - I think you will
understand the reason for the my first statement.|||Can you post a repro? Is the datatype really datetime? Also, I agree that fo
rmatting is best
performed in the client application.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Brennan" <Brennan@.discussions.microsoft.com> wrote in message
news:753F4CC7-DC7F-496E-8834-51667F2BFD0B@.microsoft.com...
> Thanks. But it still shows up as military time when I use 100.
> "Barry" wrote:
>|||Thanks I agree with you about the client. I am using smalldatetime.
My problem is that my client is a DNN portal. I am using an add in module
that let's me dynamically display the results of an SQL statement in a grid
on any selected page.
Unfortunately, it does not give me the opportunity to adjust any formatting
which was why I was trying to approach it from a Convert perspective. And I
know nothing about asp so I can't approach the problem from the client side.
I'll try some of the solutions mentions here, but I think I'm going to end u
p
writing an RS report to provide this information to our end users.
Thanks
"Scott Morris" wrote:

> Usually, formatting is best left to the client since most client languages
> have far better capabilities in this area. It isn't particularly clear wh
at
> datatypes you are using for the columns in question - the assumption is th
at
> they are both datetime (or smalldatetime). If this assumption is not vali
d,
> then you should clarify what the datatypes are and the expected formats of
> the data (if applicable). One can question the wisdom of separating these
> two intimately related bits of information into two separate columns -
> especially given the dbms support.
> If you must persist in this quest, you will most likely need to "generate"
> the appropriate information in some convoluted and complex expression (and
> possibly multiple queries). For the convert function, none of the availab
le
> formats has a space between the time and the AM/PM characters. If this ca
n
> be ignored, the 100 format is the closest - convert to this format and tak
e
> the last 7 characters (or all the characters from the last space to the en
d
> of the string). You could also use the datepart functions to strip off an
d
> convert the bits that are of interest. Experiment a bit - I think you wil
l
> understand the reason for the my first statement.
>
>

COnvert

Hi All,
I posted this query a coupe of days ago and had a few repiies but I have
only just got around to trying them out, I was trying to convert a nvarchar
values of 01112005 which this time I will explain is meant to be the !st of
November 2005, this is something that I forgot to mention last time, I am
trying to convert this to a datetime type so that I can perform some checks
and deletes based on specific dates, I was advised to convert the date to a
yyyymmdd type, but no matter how I right the convert statement the date stay
s
the same, I was using a statement like
convert(nvarchar(10),column_A,112)
This is really starting to drive me nuts as I have read lots of articles
about conversions and nothing I seem to do alters the data in anyway, am I
doing something wrong.
Thanks for any help anyone can yet again offer.
Philddmmyy is not a valid datetime format in SQL Server. So, do some string pars
ing to build a valid
datetime format. Something like:
CAST(SUBSTRING(column_A, 4, 5) + SUBSTRING(column_A, 2, 3) + SUBSTRING(colum
n_A, 2, 1) AS datetime)
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Phil" <Phil@.discussions.microsoft.com> wrote in message
news:CD78C5BE-FCE2-4BD5-B5F7-9280C20D440C@.microsoft.com...
> Hi All,
> I posted this query a coupe of days ago and had a few repiies but I have
> only just got around to trying them out, I was trying to convert a nvarcha
r
> values of 01112005 which this time I will explain is meant to be the !st o
f
> November 2005, this is something that I forgot to mention last time, I am
> trying to convert this to a datetime type so that I can perform some check
s
> and deletes based on specific dates, I was advised to convert the date to
a
> yyyymmdd type, but no matter how I right the convert statement the date st
ays
> the same, I was using a statement like
> convert(nvarchar(10),column_A,112)
> This is really starting to drive me nuts as I have read lots of articles
> about conversions and nothing I seem to do alters the data in anyway, am I
> doing something wrong.
> Thanks for any help anyone can yet again offer.
> Phil|||Tibor, I believe there's a flaw in your substrings. The proper syntax is:
SUBSTRING ( expression, start, length )
And you seem to have:
SUBSTRING ( expression, length, start )
ML
http://milambda.blogspot.com/|||Hi All,
Thanks again for the very quick replies, on your advice I have finally got
it sorted and I have checked that it returns the results that I wanted befor
e
posting back on here.
Thanks again to one and all, Phil
"ML" wrote:

> Tibor, I believe there's a flaw in your substrings. The proper syntax is:
> SUBSTRING ( expression, start, length )
> And you seem to have:
> SUBSTRING ( expression, length, start )
>
> ML
> --
> http://milambda.blogspot.com/|||There I have it from not running my code before posting. Thanks :-)
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"ML" <ML@.discussions.microsoft.com> wrote in message
news:6CB5C492-C087-4C65-92EB-6D381F877D61@.microsoft.com...
> Tibor, I believe there's a flaw in your substrings. The proper syntax is:
> SUBSTRING ( expression, start, length )
> And you seem to have:
> SUBSTRING ( expression, length, start )
>
> ML
> --
> http://milambda.blogspot.com/

Conversion query

I have 2 date variables passed into my store procedure as follows
@.StartDate datetime,
@.EndDate datetime
however I am getting a conversion error when running the command below which
says "Syntax error converting datetime from character string"
PRINT ('INSERT INTO ' + @.NewSubsList + '(SubRef)
SELECT DISTINCT SubRef
FROM Subscriptions
WHERE (PubCode = ' + @.PubCode + ') AND DateEntered >= ' + @.StartDate +
') AND (DateEntered <= ' + @.EndDate + ')')
Any suggestions would be welcome.
ThanksYou have to explictly cast the datetime values to characters like so
PRINT ('INSERT INTO ' + @.NewSubsList + '(SubRef)
SELECT DISTINCT SubRef
FROM Subscriptions
WHERE (PubCode = ' + @.PubCode + ') AND DateEntered >= '
+ Cast(@.StartDate As VarChar(20))
+ ') AND (DateEntered <= ' + Cast(@.EndDate As VarChar(20)) + ')')
Thomas
"Pete" <Pete@.discussions.microsoft.com> wrote in message
news:E78EE524-27E2-47AF-96E4-60B250AFA884@.microsoft.com...
>I have 2 date variables passed into my store procedure as follows
> @.StartDate datetime,
> @.EndDate datetime
> however I am getting a conversion error when running the command below whi
ch
> says "Syntax error converting datetime from character string"
> PRINT ('INSERT INTO ' + @.NewSubsList + '(SubRef)
> SELECT DISTINCT SubRef
> FROM Subscriptions
> WHERE (PubCode = ' + @.PubCode + ') AND DateEntered >= ' + @.StartDate +
> ') AND (DateEntered <= ' + @.EndDate + ')')
> Any suggestions would be welcome.
> Thanks

Sunday, March 25, 2012

Conversion of query from Oracle to SQL Server

Hi Friends,
Need ur help desperately. I am stuck with one of the queries which i had written in Oracle and need the same in SQL Server.Please have a look at the following query :

select * from r_tin_1099_info where instr(translate( nm_ctrl_cd , '~!@.#$%^&*()_+}{":?><`-=]['''';/., ', '*******************************' ),'*') > 0;

Basically my purpose is to replace the values in column NM_CTRL_CD having wild card characters with '*' and then select this rows to display.

However i am not able to run the same query in SQL Server since TRANSLATE is not a built in func. I have tried a lot to replace it but could only one func : REPLACE . But the same will not replace any one of the above wild characters but will replace the entire pattern.Please note that it should be able replace even if one of the wild card characters are present in the string and not necessarily the entire pattern shown above.

please reply ASAP since i am working and need this query to fix a defect.

Thanks in advance.Hi all,
Can somebody please reply to my query mentioned above !!!|||I'd suggest using:SELECT *
FROM r_tin_1099_info
WHERE nm_ctrl_cd LIKE '%[]~!@.#$%^&*()_+}{":?><`-=[]%'
-PatP|||Hey thanks a ton... I will try this out and let you know about the results !!!|||Hi,
The query u have sent does not return any result even though the data is there in the table.Can you please help us out with the query !!

Thanks|||Sorry, I was trying to avoid using escape characters and that got me into trouble. A better solution is:SELECT *
FROM r_tin_1099_info
WHERE nm_ctrl_cd LIKE '%[~!@.#$%^&*()_+}{":?><`x-=x]['';/., ]%' ESCAPE 'x'-PatP|||hey Pat... thanks a lot.. this is working fine... just another question... do u knw any equivalent func for TRANSLATE(in DB2)... bcoz i have a query in DB2 which needs to be translated in SQL Server and since TRANSLATE is not a built in func.. i am not able to execute the same query. the query is as follows:

update r_tin_1099_info set nm_ctrl_cd = substr(replace(translate( coalesce(last_nm,tin_nm_1), '', '~!@.#$%^&*()_+}{":?><`-=]['''';/., ' ),' ',''),1,4) where locate('*',translate( nm_ctrl_cd , '*******************************', '~!@.#$%^&*()_+}{":?><`-=]['''';/., ' )) > 0

I know i mite be asking to much from you.. but it will gr88 if u can guide me with this query as well !!

Thanks.|||Because the second argument to the Translate() call is an empty string, the Translate function will do nothing, it is meaningless so it can be discarded. That leaves you with:UPDATE r_tin_1099_info
SET nm_ctrl_cd = substr(replace(coalesce(last_nm, tin_nm_1), ' ', ''), 1, 4)
WHERE nm_ctrl_cd LIKE '%[~!@.#$%^&*()_+}{":?><`x-=x]['';/., ]%' ESCAPE 'x'-PatP|||hey pat... i tried ur query... its executing without any errors but doesnt seem to update the records... the values having wild characters are not updated and still contain the wild characters... Can you please help me out with this

thanks.|||If you can tell me what you want, I can probably help. The code that you posted in your last question ought to have exactly the same effect as the code that I posted in response to it, but that doesn't appear to be what you actually want.

As I've given you several examples to work from, you ought to be able to get pretty close to what you want on your own. If not, please post:

1) whatever DML you have working
2) A DDL script to build your schema
3) At least a few sample rows of data (BCP native format would be preferred)
4) An example of the output that you'd like from your query

I'll help you, but I can't read your mind and I won't actually do your job for you.

-PatP

Conversion of Access query using First() Aggregate

All,
I am trying to figure out how to convert this particular query, and am
stumped...
SELECT tCollatList.CollatID, tCollatList.ListCatID, tlListCategory.Category,
First(tlListCategory.[CatWholeVal%]) AS [FirstOfCatWholeVal%],
First(tlListCategory.Unit) AS FirstOfUnit, First(tlListCategory.[$Unit]) AS
[FirstOf$Unit], Sum([tCollatList]![ColListIncDec]) AS Balance,
[Balance]*[FirstOf$Unit] AS BalValue, [BalValue]*[FirstOfCatWholeVal%] AS
BalWhole
FROM tCollatList LEFT JOIN tlListCategory ON tCollatList.ListCatID =
tlListCategory.ListCatID
GROUP BY tCollatList.CollatID, tCollatList.ListCatID, tlListCategory.Categor
y
HAVING (((tCollatList.CollatID)=9));
SQL server doesn't support 'First(tlListCategory.[$Unit]) AS [FirstOf$Unit]'
Can someone please tell me what I can do, if anything to duplicate this
functionallity?
ThanksScottW wrote:
> All,
> I am trying to figure out how to convert this particular query, and am
> stumped...
> SELECT tCollatList.CollatID, tCollatList.ListCatID, tlListCategory.Categor
y,
> First(tlListCategory.[CatWholeVal%]) AS [FirstOfCatWholeVal%],
> First(tlListCategory.Unit) AS FirstOfUnit, First(tlListCategory.[$Unit]) A
S
> [FirstOf$Unit], Sum([tCollatList]![ColListIncDec]) AS Balance,
> [Balance]*[FirstOf$Unit] AS BalValue, [BalValue]*[FirstOfCatWholeVal%] AS
> BalWhole
> FROM tCollatList LEFT JOIN tlListCategory ON tCollatList.ListCatID =
> tlListCategory.ListCatID
> GROUP BY tCollatList.CollatID, tCollatList.ListCatID, tlListCategory.Categ
ory
> HAVING (((tCollatList.CollatID)=9));
> SQL server doesn't support 'First(tlListCategory.[$Unit]) AS [FirstOf$Unit
]'
> Can someone please tell me what I can do, if anything to duplicate this
> functionallity?
> Thanks
The problem is that FIRST is not a real aggregate function, even in
Access. Access's FIRST and LAST functions just return some arbitrary
value from the set of rows in question. So you might as well use MIN or
MAX instead. If you want a different answer then you need a better
specification of what you mean by "first" and "last". Tables have no
inherent order and nor do query results unless you use ORDER BY.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Hello David,
The code provided was specific, using SQL Server 2000, specifically it
says First is an unknown keyword.
As for there being arbitrary values, not in this case. Each value in the
joined table is identical, which is why we need only one record, so the
values from the other table can be summed. I guess that being said, usinfg
min or max should return the desired results. Thoughts?
Thanks
"David Portas" wrote:

> ScottW wrote:
> The problem is that FIRST is not a real aggregate function, even in
> Access. Access's FIRST and LAST functions just return some arbitrary
> value from the set of rows in question. So you might as well use MIN or
> MAX instead. If you want a different answer then you need a better
> specification of what you mean by "first" and "last". Tables have no
> inherent order and nor do query results unless you use ORDER BY.
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||ScottW wrote:
> Hello David,
> The code provided was specific, using SQL Server 2000, specifically it
> says First is an unknown keyword.
That's right.

> As for there being arbitrary values, not in this case. Each value in the
> joined table is identical, which is why we need only one record, so the
> values from the other table can be summed.
In that case you can just add CatWholeVal%, Unit and $Unit to the GROUP
BY list. Then you don't need to use an aggregate function at all.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--sqlsql

Thursday, March 22, 2012

conversion from Access query to mssql query

Hello Guys

I am chaging the connectivity of MSaccess2K to sqlserver
the code is written in vb editor of access
i have established the connection string
but the following query is generating error of
invalid object name

strSQL = SELECT DISTINCT [Sites Union Controls].Description,
[Sites Union Controls].[Rous Reportable Site], [Sites Union Controls].[Type], Samples.SequenceNumber FROM Jobs INNER JOIN ([Sites Union Controls] INNER JOIN Samples ON [Sites Union Controls].SiteSerial = Samples.SiteSerial) ON Jobs.JobSerial = Samples.JobSerial
WHERE ((Jobs.JobSerial) = " & intJobSerial & ") ORDER BY Samples.SequenceNumber

I am getting an error invalid object name sites union controls

can't we do union of two tables as above in mssql
Please Help

Thanks In AdvanceI'm sure some one will correct me if Im wrong but I dont think this query will ever work in SQL Server, it does look like something that might run in access though.

Ive had problems like this before, Access loves adding in brackets () that just get in the way and confuse things in SQL Server. It also seams to list all the tables then join them in the FROM statement which is not s SQL thing either.

I think your also going to have a problem with the WHERE clause, namely the part " & intJobSerial & " reefers to a variable in Access. Even if you have created the variable in SQL Server the syntax is still wrong

Your query doesnt look like a union query, but a standard select query gone a bit wrong in the FROM part. Your query should look something like

DECLARE @.intJobSerial VARCHAR(50) -- this creates the variable as a 50 character text field, don't need this bit if youve done it already

SET @.intJobSerial = 'XXX' -- this sets the variable to XXX, don't need this bit if youve done it already

SELECT DISTINCT [Sites Union Controls].[Description],[Sites Union Controls].[Rous Reportable Site], [Sites Union Controls].Type, Samples.SequenceNumber

FROM [Sites Union Controls]
INNER JOIN Samples
ON [Sites Union Controls].SiteSerial = Samples.SiteSerial
INNER JOIN Jobs
ON Jobs.JobSerial = Samples.JobSerial

WHERE Jobs.JobSerial = @.intJobSerial

ORDER BY Samples.SequenceNumber

The invalid object sites union controls in actually the table used the query, Im guessing its because the FROM Part was all messed up at it was the first thing it came across after it went wrong.

Hope this helps|||Hello,

Trying by used the next name Sites_Union_Controls because I'm not sure that you can have a name with blanc characters

Good luck

Sylvie

Quote:

Originally Posted by aakash

Hello Guys

I am chaging the connectivity of MSaccess2K to sqlserver
the code is written in vb editor of access
i have established the connection string
but the following query is generating error of
invalid object name

strSQL = SELECT DISTINCT [Sites Union Controls].Description,
[Sites Union Controls].[Rous Reportable Site], [Sites Union Controls].[Type], Samples.SequenceNumber FROM Jobs INNER JOIN ([Sites Union Controls] INNER JOIN Samples ON [Sites Union Controls].SiteSerial = Samples.SiteSerial) ON Jobs.JobSerial = Samples.JobSerial
WHERE ((Jobs.JobSerial) = " & intJobSerial & ") ORDER BY Samples.SequenceNumber

I am getting an error invalid object name sites union controls

can't we do union of two tables as above in mssql
Please Help

Thanks In Advance

|||Hey, a couple of points...
SQL uses + for concatenation so you need to change your where statement to
((Jobs.JobSerial) = " + @.intJobSerial + ")

JohnK is right, if intJobSerial is a local variable then it needs to be declared and it must begin with an @..

There is nothing wrong with the FROM statement, it's a little unusual to delay the two ON clauses at the end but this gives a different result set because nulls in the 3rd table, in your query SAMPLES, can be handled differently this way. It's more effective if your mixing Left Outer and Inner Joins, however.

The biggest thing I see is that the permissions on the SQL table [Sites Union Controls] may be different than what you expect. You should probably be using a full reference to it as [database].[owner].[table] to at least eliminate the possibility that your error is a security setup problem.

Tom|||Sites Union Controls, was query in old ms access project which was connected to ms access database i am changing connectivity to ms sql 2000 ,none of the above solutions seem to be working ,
please help

Conversion error

I am getting the error message Error converting data type varchar to float when running the following query:

Code Snippet

select top 175816
AV.intItemID,
AV.intAttrID,
-- AV.vchValue,
CAST(AV.vchValue AS float) AS Test,
0
from tblAttrVals AV
join tblAttributes AA
on AA.intAttributeID = AV.intAttrID
and AA.intDataTypeID in (2, 3)
and (1 = isnumeric (AV.vchValue))
order by AV.intItemID, AV.intAttrID

Here is what is strange. If I bump the top count down by one it succeeds. And even stranger, if I leave the top count the same and uncomment out the line in the select statement that shows the value being converted it succeeds.

Any ideas? This seems like a bug.

Chris:

Can you show us the specific data that is giving you trouble?

|||

I found the issue. It actually had nothing to do with the data that is being returned. It had to do with the data not being returned.

Here is the info from a post that helped me:

The problem is that SQL Server 2005 is more aggressive in terms of evaluating expressions in your query and moving them to different stages of the query plan. This might result in conversion error like in your case if the CAST gets computed before the WHERE clause checks. So there is no guarantee that the expressions in the WHERE clause will be computed first. This was true even in SQL Server 2000 except that you probably never hit it for your schema/data set. You can get the same error there also if the query plan changes.

To resolve the problem, you need to either correct your data model to represent the values correctly. Use float if your data is float - don't mix values from different domains. Or you will have to use CASE in the SELECT list to avoid the conversion problem. Note that using CASE expression is the only way to control order of execution of various expressions. See link below for more details (search for unsafe expressions):

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

To summarize you have two solutions:

1. Fix your data model / schema so you represent the values in their proper domain (not float values in varchar and mixing various values in string)
2. Or modify your SELECT in the 2nd view to:

SELECT cast(CASE WHEN dwpId LIKE '[0-9]%' THEN dwpId END as int) as dwpId, startDate, endDate
FROM View1

Note that even above check is not entirely correct because not all values that have just numeric digits can be successfully converted to int. You might get overflow errors for example. You could use ISNUMERIC but that checks for integer, numeric, and money conversions so it will let more data through. So it is best you correct your schema to avoid all these issues.

sqlsql

Conversion Access Query to SQL Server 2000

SELECT DISTINCTROW OILPALM.NAME, formatyear([year]) AS yearDisplay, OILPALM.YEAR, OILPALM.UNIT, OILPALM.BLOCK, OILPALM.BlockInYield, [Y_01_total_ton]+[Y_02_total_ton]+[Y_03_total_ton]+[Y_04_total_ton]+[Y_05_total_ton]+[Y_06_total_ton]+[Y_07_total_ton]+[Y_08_total_ton]+[Y_09_total_ton]+[Y_10_total_ton]+[Y_11_total_ton]+[Y_12_total_ton] AS Production, IIf([m_a]>0,[Production]/[m_a],0) AS [Avg Yield], ([Y_TH_POT]*IIf([blockinyield]=True,[size],0))*(([YieldP_01]+[YieldP_02]+[YieldP_03]+[YieldP_04]+[YieldP_05]+[YieldP_06]+[YieldP_07]+[YieldP_08]+[YieldP_09]+[YieldP_10]+[YieldP_11]+[YieldP_12])/100) AS TotalTon_Pot, IIf(IIf([blockinyield]=True,[SIZE],0)>0,([Y_TH_POT]*IIf([oilpalm].[blockinyield]=True,[oilpalm].[size],0))*(([YieldP_01]+[YieldP_02]+[YieldP_03]+[YieldP_04]+[YieldP_05]+[YieldP_06]+[YieldP_07]+[YieldP_08]+[YieldP_09]+[YieldP_10]+[YieldP_11]+[YieldP_12])/100)/IIf([blockinyield]=True,[SIZE],0),0) AS [Yield pot], [Avg Yield]-[Yield pot] AS [Yield Gap], OILPALM.Y_KGB AS [Avg bunchweight], IIf([TotalTree]>0,[Total bunches]/[TotalTree],0) AS [Avg Bunch No], OILPALM.SIZE AS [Total size], OILPALM.Y_TOTAL_mandays AS [Total workforce], OILPALM.Y_AVG_harvest_int AS Avg_Harvest_int, OILPALM.Y_AVG_harvest_int AS sum_Harvest_int_sum, IIf([Y_AVG_harvest_int]>0,1,0) AS rec_Harvest_int, IIf([rec_Harvest_int]>0,[sum_Harvest_int_sum]/[rec_Harvest_int],0) AS Calc_Harvest_int, OILPALM.Y_per_manday AS Avg_YMD, [Y_01_TOTAL_bunches]+[Y_02_TOTAL_bunches]+[Y_03_TOTAL_bunches]+[Y_04_TOTAL_bunches]+[Y_05_TOTAL_bunches]+[Y_06_TOTAL_bunches]+[Y_07_TOTAL_bunches]+[Y_08_TOTAL_bunches]+[Y_09_TOTAL_bunches]+[Y_10_TOTAL_bunches]+[Y_11_TOTAL_bunches]+[Y_12_TOTAL_bunches] AS [Total bunches], OILPALM.Y_TOTAL_mandays AS [Total manday], IIf([Blockinyield]=True,IIf([TC_M]>0,[TC_M],[TC_DENS]*[size]),0) AS TotalTree, OILPALM.TC_M, IIf([TotalTree]>0,([Production]*1000)/[TotalTree],0) AS [Avg bunchweighMTree], IIf([Total workforce]>0,[Production]/[Total workforce],0) AS TMd, (IIf(([oilpalm]![blockinyield]=-1),[OILPALM]![SIZE],0)) AS M_A
FROM OILPALM INNER JOIN SYS_soil_type ON OILPALM.SOILTYPE = SYS_soil_type.SoilType
ORDER BY OILPALM.YEAR DESC , OILPALM.UNIT, OILPALM.BLOCK;

Please Help Me....

I suggest that you take the time to work through the suggestions that have been provided to your previous posts until you understand the process.

When you work through the process and begin to understand the process, you will be able to work these out for yourself. (Otherwise, we might think that you are just trying to get folks to do your work for you. And that probably wouldn't be fair to you ...)

|||

1. Change all your IIF(CONDITION,TRUE STMT, FALSE STMT)

CASE WHEN CONDITION THEN TRUE STMT ELSE FALSE STMT END

2. You need to convert your formatyear macro logic to SQL Server

conversion *= to left outer joins not yielding desired results

Hi

I have a query which works fine on sql 2000 with *= but doesn't yield the same when converted to 2005 using joins

Here is the original query

SELECT tmpex.pa_number, tmpex.big_deal_id, tmpex.custname, c.iso_code, c.name, pf.product_family_name,
ISNULL(dcts.tatsla, tscd.tatsla), tmpex.psm_contact
FROM country c, product_family pf,
ship_to_country sc, dealcountry_tatsla dcts, tatsla_countrydefaults tscd, #TAT_EXPORT_DEALVALUES tmpex
WHERE
c.id_country = sc.id_country
AND sc.id_deal = tmpex.id_deal

AND sc.id_country *= dcts.id_country

AND sc.id_deal *= dcts.id_deal
AND pf.id_product_family *= dcts.id_product_family
AND sc.id_country = tscd.id_country
AND pf.id_product_family = tscd.id_product_family

The Converted one is below

select tmpex.pa_number, tmpex.big_deal_id, tmpex.custname, c.iso_code, c.name, pf.product_family_name,
ISNULL(dcts.tatsla, tscd.tatsla), tmpex.psm_contact
from
ship_to_country sc INNER JOIN country c
ON sc.id_country = c.id_country
INNER JOIN #TAT_EXPORT_DEALVALUES tmpex
ON (sc.id_deal = tmpex.id_deal )
INNER JOIN tatsla_countrydefaults tscd1
ON (sc.id_country = tscd1.id_country)
LEFT OUTER JOIN
dealcountry_tatsla dcts
ON (sc.id_country = dcts.id_country and sc.id_deal=dcts.id_deal )
LEFT OUTER JOIN product_family pf
ON (pf.id_product_family = dcts.id_product_family)
INNER JOIN tatsla_countrydefaults tscd
ON (pf.id_product_family = tscd.id_product_family)

Please let me know whether I am missing something

The join query results in cartesian product

If I remember old style syntax correctly, the new version will looks like this:

SELECT tmpex.pa_number, tmpex.big_deal_id, tmpex.custname, c.iso_code, c.name, pf.product_family_name,
ISNULL(dcts.tatsla, tscd.tatsla), tmpex.psm_contact
FROM country c
inner join ship_to_country sc on c.id_country = sc.id_country
inner join #TAT_EXPORT_DEALVALUES tmpex on sc.id_deal = tmpex.id_deal
inner join tatsla_countrydefaults tscd on sc.id_country = tscd.id_country
inner join product_family pf on pf.id_product_family = tscd.id_product_family
left join dealcountry_tatsla dcts on sc.id_country = dcts.id_country
and sc.id_deal = dcts.id_deal and pf.id_product_family = dcts.id_product_family

Not sure it is equivalent, though, so thorough testing is highly recommended.|||Your Query seems to be correct. Have you checked the result set. Is there any flaw in that.|||No, I've not checked this - I have no underlying data to test on. If I had, I'd have no doubt Smile

But since you have both the tables and the data, you always may test its correctness - either on MSSQL 2000 or, if all that you have is MSSQL 2005, on a separate database with compatibility level set to 80. In the latter case, both queries will work even on 2005.sqlsql