Showing posts with label records. Show all posts
Showing posts with label records. Show all posts

Friday, March 30, 2012

please help me to cearte this stored procedure

Hi ,

I want to make a report of records of a table, there is abut 15 fields that this report based on them , so we need a select query like this

Select f1,f2from Table1where f3=@.f3and f4=@.f4 and ….and f17=@.f17

-- f1 = field1 and ….

The problem is sometimes @.fs are empty, for example if @.f4was empty so "and f4=@.f4" should be excluded from the select query .(and it means there is no limitation for f4 field)

I know, probably I couldn't explain my purpose very well,Embarrassed but I hope somebody kindly try to understand it .

how can I perform that in a stored procedure?

Please help me

Thank you

try it like this:

SELECT f1,f2FROM Table1WHERE (f3=@.f3OR @.f3ISNULL)AND (f4=@.f4OR @.f4ISNULL)AND ….AND (f17=@.f17OR @.f17ISNULL)
|||

Is in your example @.f4 empty or null? I think null, so I created the following query for you:

Select

f1from table1where f1= @.f1and(f4= @.f4or @.f4isnull)

This query selects all the records where f1 matches @.f1 and f4 matches @.f4 or @.f4 is null (and will be ignored then).

I hope this helps

Richard

|||

mbanavige & richardsoeteman.net thank you very, very much!.

|||

Hi

Assume there are 3 tables like these:

Table0

Primary key

Name

1

Name1

2

Name2

3

Name3

Table 1:

Foreign key

Column1

1

Data1

2

Data1

Table2:

Foreign key

Column2

2

Data2

3

Data2

And there are 2 parameters that they may be null: @.Data1 and @.Data2

I need a select query that

-selects "Name2" from Table0 if:

@.Data1="Data1"

@.Data2="Data2"

-selects "Name1, Name2" from Table0 if:

@.Data1="Data1"

@.Data2=null

-selects "Name2, Name3" from Table0 if:

@.Data1=null

@.Data2="Data2"

And selects "Name1, Name2, Name3" from Table0 if both of@.Data1 &@.Data2 wasnull.

I know I did not explain very well again but it's the final step of my project and I really need help. So please help me again Embarrassed

Thanks,

|||

Same concept:

Read this post:http://forums.asp.net/thread/1440706.aspx

|||

thank you Mike,

What about parameters that areint ordecimal and we want to ignore them , they can not benull ,they can be 0.

thank you Mike,

|||

You can use the same concept

Select

f1from table1where(f1= @.f1or @.f1=0)

|||Thank you Richard,

Monday, March 26, 2012

Please Help

I am trying to pull the last 30 records in a table. I'm trying to write a
dynamic stored procedure in order to do this. I am joining a couple tables
and the table i need to get the 30 records out of is the second table. I
can't seem to get it to work with my code. Below is the code that I am using
to try to do this, I have declared the variables earlier in this procedure:
(Select Distinct LotID, @.LowNum = max(LotID)-30, @.HighNum = max(LotID)
From dbo.schedulegovcom
Where LotID<=@.HighNum
and >=@.LowNum
Group by LotID) pTry:
SELECT TOP 30
[field list]
FROM
dbo.schedulegovcom
ORDER BY
LotID DESC
Mike
"A.B." <AB@.discussions.microsoft.com> wrote in message
news:F449DAD0-7B92-4E1A-9676-1604C2D79D3A@.microsoft.com...
>I am trying to pull the last 30 records in a table. I'm trying to write a
> dynamic stored procedure in order to do this. I am joining a couple tables
> and the table i need to get the 30 records out of is the second table. I
> can't seem to get it to work with my code. Below is the code that I am
> using
> to try to do this, I have declared the variables earlier in this
> procedure:
> (Select Distinct LotID, @.LowNum = max(LotID)-30, @.HighNum = max(LotID)
> From dbo.schedulegovcom
> Where LotID<=@.HighNum
> and >=@.LowNum
> Group by LotID) p|||You can not mix resultset with assigning value to a variable in the same
select statement.
-- wrong
select @.i = orderid, customerid from dbo.orders
AMB
"A.B." wrote:

> I am trying to pull the last 30 records in a table. I'm trying to write a
> dynamic stored procedure in order to do this. I am joining a couple tables
> and the table i need to get the 30 records out of is the second table. I
> can't seem to get it to work with my code. Below is the code that I am usi
ng
> to try to do this, I have declared the variables earlier in this procedure
:
> (Select Distinct LotID, @.LowNum = max(LotID)-30, @.HighNum = max(LotID)
> From dbo.schedulegovcom
> Where LotID<=@.HighNum
> and >=@.LowNum
> Group by LotID) p|||Thanks that worked
"Mike Jansen" wrote:

> Try:
> SELECT TOP 30
> [field list]
> FROM
> dbo.schedulegovcom
> ORDER BY
> LotID DESC
> Mike
> "A.B." <AB@.discussions.microsoft.com> wrote in message
> news:F449DAD0-7B92-4E1A-9676-1604C2D79D3A@.microsoft.com...
>
>

Friday, March 23, 2012

please check this not null SQL String

the SQL string below worked, and then started bringing up every record.
it should only select records with a value in at least one of the columns, but it apears to be suggesting that all records have some data in one of the columns. if I check the database or the output on the web page there apears to be no data. ?? confused.

"SELECT id, make, model FROM vehicles WHERE workToBeDone1 IS NOT NULL OR workToBeDone2 IS NOT NULL OR workToBeDone3 IS NOT NULL OR workToBeDone4 IS NOT NULL OR workToBeDone5 IS NOT NULL"

Any ideas how I could implement this more robustly?
cheers
MSorry, doesn't work that way.

You need a condition for each column|||Cheat. Execute:
"SELECT id, make, model
, CAST(workToBeDone1 AS VARBINARY(10)) AS w1
, CAST(workToBeDone2 AS VARBINARY(10)) AS w2
, CAST(workToBeDone3 AS VARBINARY(10)) AS w3
, CAST(workToBeDone4 AS VARBINARY(10)) AS w4
, CAST(workToBeDone5 AS VARBINARY(10)) AS w5
FROM vehicles
WHERE workToBeDone1 IS NOT NULL
OR workToBeDone2 IS NOT NULL
OR workToBeDone3 IS NOT NULL
OR workToBeDone4 IS NOT NULL
OR workToBeDone5 IS NOT NULL"If the Cast() columns do not ALL show NULL as their value, then you have data in the offending column(s). Empty strings, and sometimes even the constant "NULL" have been known to sneak into tables when you do not expect them!

-PatP|||thanks guys.
I'm sure my version was working fine until the database seemed to put something invisible into the columns.
I tried your code Pat but it returns "ADODB.Recordset error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal."

What does the 'as w1' part do?

my code looks like this:
"SELECT id, make, model, CAST(workToBeDone1 AS VARBINARY(10)) AS w1, CAST(workToBeDone2 AS VARBINARY(10)) AS w2, CAST(workToBeDone3 AS VARBINARY(10)) AS w3, CAST(workToBeDone4 AS VARBINARY(10)) AS w4, CAST(workToBeDone5 AS VARBINARY(10)) AS w5 FROM vehicles WHERE workToBeDone1 IS NOT NULL OR workToBeDone2 IS NOT NULL OR workToBeDone3 IS NOT NULL OR workToBeDone4 IS NOT NULL OR workToBeDone5 IS NOT NULL"|||Drop the quotes from around the SQL statement for starters ;)

For the 'As w1' try running this

SELECT id As 'Example'
FROM vehicles|||thanks georgev
sorry, I missed a crucial bit re the quotes: SQLstring="Select..."
I'll have a play with your example and see if I get it.|||nope, sorry, couldn't figure out what I am supposed to do with your example George.|||Run the thing in QA and see if you notice something.
Basically it's giving the column an alias http://doc.ddart.net/mssql/sql70/sa-ses_3.htm - scroll down to columns_alias :p|||can't use QA on this, I have to run scripts on pages on the server.
Not sure why I need aliases.
My database columns seem to contain invisible data, is there a way to discover if the columns have any meaningful data in them? NULL seems to be a bit flakey

I need to find cars that need work done - i.e. someone has inputted something like: 'replace tyres' in one of the workToBeDone fields for a Volvo. but my search is returning every car in the database because it is seeing something in the columns. (I think!).

I tried casting as varchar(255) - made no difference|||The "as W1" simply assigns an alias to the column as GeorgeV observed. It appears that your ADO implementation doesn't like the aliases.

If Query Anylyzer (or its equivalent) is available, then I'd use it instead of writing/changing code to support your ADO implementation. Operative word being "should", you should be able to simply drop the column names and move on without them.

-PatP|||And by drop the column names we don't mean physically dropping the columns... Just remove the "As ..." from your SQL statement.

The reason the aliases were applied in the first place because as soon as you perform any function on a column it loses the reference to the column name (because it's not the same as the column data any more!). The Aliases allow us to access the columns by referenec in ADO (or so I believe).|||I dropped the aliases, but it made no difference, I'm still getting:
'Item cannot be found in the collection corresponding to the requested name or ordinal',|||Ok, let's try to solve the problem from a different vector and execute:"SELECT id, make, model
, CASE WHEN workToBeDone1 IS NULL THEN 0 WHEN 0 = Len(workToBeDone1) THEN 1 ELSE 2 END
, CASE WHEN workToBeDone2 IS NULL THEN 0 WHEN 0 = Len(workToBeDone2) THEN 1 ELSE 2 END
, CASE WHEN workToBeDone3 IS NULL THEN 0 WHEN 0 = Len(workToBeDone3) THEN 1 ELSE 2 END
, CASE WHEN workToBeDone4 IS NULL THEN 0 WHEN 0 = Len(workToBeDone4) THEN 1 ELSE 2 END
, CASE WHEN workToBeDone5 IS NULL THEN 0 WHEN 0 = Len(workToBeDone5) THEN 1 ELSE 2 END
FROM vehicles
WHERE workToBeDone1 IS NOT NULL
OR workToBeDone2 IS NOT NULL
OR workToBeDone3 IS NOT NULL
OR workToBeDone4 IS NOT NULL
OR workToBeDone5 IS NOT NULL"-PatP|||Thanks Pat,
still getting the same error. here's more of the code (inc. your bit) to give you a bigger picture:

Set linkRS = Server.CreateObject("ADODB.Recordset")

salePrice = request.Form("salePrice")
make=request.Form("make")
model2show=request.Form("model2show")
salePrice=request.Form("salePrice")
fuel=request.Form("fuel")
sold=request.Form("sold")
workOutstanding=request.Form("workOutstanding")
notOnWebsite=request.Form("notOnWebsite")

strSQL="SELECT id, make, model, model2show, registration, price FROM vehicles WHERE price BETWEEN "& salePrice &""
if make <> "" then strSQL = strSQL & " AND make = '" & make & "'"

if fuel <> "" then strSQL = strSQL & " AND fuel = '" & fuel & "'"

if model2show <> "" then strSQL = strSQL & " AND model2show = '" & model2show & "'"

if sold = "yes" then strSQL = strSQL & " AND sold = 'yes'"

if workOutstanding = "yes" then strSQL = "SELECT id, make, model, CASE WHEN workToBeDone1 IS NULL THEN 0 WHEN 0 = Len(workToBeDone1) THEN 1 ELSE 2 END, CASE WHEN workToBeDone2 IS NULL THEN 0 WHEN 0 = Len(workToBeDone2) THEN 1 ELSE 2 END, CASE WHEN workToBeDone3 IS NULL THEN 0 WHEN 0 = Len(workToBeDone3) THEN 1 ELSE 2 END, CASE WHEN workToBeDone4 IS NULL THEN 0 WHEN 0 = Len(workToBeDone4) THEN 1 ELSE 2 END, CASE WHEN workToBeDone5 IS NULL THEN 0 WHEN 0 = Len(workToBeDone5) THEN 1 ELSE 2 END FROM vehicles WHERE workToBeDone1 IS NOT NULL OR workToBeDone2 IS NOT NULL OR workToBeDone3 IS NOT NULL OR workToBeDone4 IS NOT NULL OR workToBeDone5 IS NOT NULL"

if notOnWebsite = "yes" then strSQL = strSQL & " AND active = 'no'"

strSQL = strSQL & " ORDER BY make"
'response.Write(strSQL)
linkRS.Open strSQL, oConn, 2, 3
if (linkRS.BOF and linkRS.EOF) then
response.Write("<p class=""inputRed"">No vehicles to display - try selecting fewer parameters</p>")
else
linkRS.moveFirst
Do while not linkRS.eof
make = linkRS("make")
'etc.
'etc.

most of this works fine, but the error message is odd because those fields do exist.|||Uncomment your 'response.Write(strSQL) and post the result.
First glance suggests you have a problem with your BETWEEN statement|||here you go:
SELECT id, make, model, CASE WHEN workToBeDone1 IS NULL THEN 0 WHEN 0 = Len(workToBeDone1) THEN 1 ELSE 2 END, CASE WHEN workToBeDone2 IS NULL THEN 0 WHEN 0 = Len(workToBeDone2) THEN 1 ELSE 2 END, CASE WHEN workToBeDone3 IS NULL THEN 0 WHEN 0 = Len(workToBeDone3) THEN 1 ELSE 2 END, CASE WHEN workToBeDone4 IS NULL THEN 0 WHEN 0 = Len(workToBeDone4) THEN 1 ELSE 2 END, CASE WHEN workToBeDone5 IS NULL THEN 0 WHEN 0 = Len(workToBeDone5) THEN 1 ELSE 2 END FROM vehicles WHERE workToBeDone1 IS NOT NULL OR workToBeDone2 IS NOT NULL OR workToBeDone3 IS NOT NULL OR workToBeDone4 IS NOT NULL OR workToBeDone5 IS NOT NULL ORDER BY make|||Maybe it contain spaces, try this
where coalesce(workToBeDone1,workToBeDone2,workToBeDone3 ,workToBeDone4,workToBeDone5,'') != ''|||thanks,
same error msg tho'

Tuesday, March 20, 2012

placing table on the memory

Hello there
I have reference localAreaCode table with 3000 records , i need to check on
existing phone table that the area code exist on LocalAreaCode table.
So far the query worked very slow.
Is there a way to place the LocalAreaCode table at the memory, to inprove
perfomance?Hi Roy,
In SQL Server 2000 you can use:
1) DBCC PINTABLE
2) sp_tableoption
See Books Online for more info about this.
I'm pretty sure that DBCC PINTABLE does nothing in SQL Server 2005 and
for sp_tableoption the choice to pin a table in memory is no longer
there. The rationale is that using these options can cause bad things
to happen. For example, in SQL Server 2005 Books Online we have the
following in the DBCC PINTABLE entry:
==============================
This functionality was introduced for performance in SQL Server version
6.5. DBCC PINTABLE has highly unwanted side-effects. These include the
potential to damage the buffer pool. DBCC PINTABLE is not required and
has been removed to prevent additional problems. The syntax for this
command still works but does not affect the server.
==============================
Sorry I can't be of more help|||Maybe we should first take look at the query. Please post it.
Also check the execution plan to see whether indexes are used properly. The
table is indexed, isn't it?
ML
http://milambda.blogspot.com/|||You could do this in 2000, using sp_tableoption. This was misused, though so
I believe that removed
it in 2005. If the table is accessed frequently enough, it will be cache in
memory, especially with
only 3000 rows. Still, you want to make sure that queries against it are eff
icient (create
supporting indexes etc).
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Roy Goldhammer" <roy@.hotmail.com> wrote in message news:uetz2fwfGHA.4276@.TK2MSFTNGP03.phx.
gbl...
> Hello there
> I have reference localAreaCode table with 3000 records , i need to check o
n existing phone table
> that the area code exist on LocalAreaCode table.
> So far the query worked very slow.
> Is there a way to place the LocalAreaCode table at the memory, to inprove
perfomance?
>|||With only 3000 rows this should never be slow, so I suspect problems
with the table design or the query. You need to post the table
design, all keys and indexes, and the query that is slow.
Roy Harvey
Beacon Falls, CT
On Wed, 24 May 2006 10:58:04 +0300, "Roy Goldhammer" <roy@.hotmail.com>
wrote:

>Hello there
>I have reference localAreaCode table with 3000 records , i need to check on
>existing phone table that the area code exist on LocalAreaCode table.
>So far the query worked very slow.
>Is there a way to place the LocalAreaCode table at the memory, to inprove
>perfomance?
>

Placing multiple records on a single line (variables)

Hi, I am new to Crystal Reports, but I know Basic and other programming. I have Crystal Reports XI and am pulling data from our ERP/MRP system, Epicor Vista (Progress DB).

I've been asked to figure out a Crystal Reports for our company (I get thrown into these projects). I know what the report should look like and I know how I would go about some VB code in a macro in Excel if all the data was in worksheets(i.e. like tables).

Below is the data. Any help would be SO appreciated. So far I'm loving Crystal Reports and I can't wait to get some reports our company can start using but I'm stuck on understanding the timing and connection of formulas with the records.

Table1 "JobMtl"
Field "JobComplete":String
Field "JobNum":String
Table2 "JobOper"
Field "OpComplete":Boolean
Field "OprSeq":Number

{JobMtl.JobComplete}
False
True
{JobMtl.JobNum}
2010
2011
{JobOper.Complete}
False
True
{JobOper.OprSeq}
10
20
30
40

Let's say I dragged all 4 fields into a report. It would look like this.

JobNum JobComplete OprSeq OpComplete
2010 False 10 True
2010 False 20 True
2010 False 30 False
2010 False 40 False
2011 False 10 True
2011 False 20 False
2011 False 30 False

I would it to read like this

JobNum JobComplete PrevOp CurrOp NextOp
2010 False 20 30 40
2011 False 10 20 30

**Note: {JobMtl.JobComplete} will be used so I am only reporting jobs that are "not complete". I guess it means nothing to you guys, but I put it here because I was not sure if this will be involved in a formula.

Thanks,
Anthony

My email is ls1z282002_at_yahoo.com (replace "_at_" => "@.") if you would a *.RPT with the data I've shown.Check your e-mail.|||Come on
We all want to see the solution|||Here's what I got from her.

There is a second report that somone from another forum helped me on. I actually need to combine both of these into one because I like the report from SvB_NY because she mad the operations a single String. So I need to do some combining of the two.

I have another question that I'm posting below this.

Anthony|||After showing this to everyone at work, they of course asked for more detail in the report :)

What we have is for each operation {JobOper.OprSeq} it may be an Outsourced (There is a boolean field {JobOper.OprSeq}) that states whether that Operation is outsourced. If it is outsourced they want me to list the PONum & POLn. I know this is simple and I thought so too! I even got it too work! So here's the snag...if the Job does not have any outsourced operations it gets skipped in my report! My reasoning is our ERP software doesn't actually make a index for PO's if that job does not have any PO's against it. Makes sense to me. So how do I handle this?

In the report I attached there should be 3 jobs
2010
2011 => Not shown because no outsourced operations
2012

Am I going to have to create 2 seperate reports, save all the information in arrays. Then match up the arrays with some code and print out a report?

Thanks,
Anthony|||SvB_NY, Thanks for all the help!

I got my report to work and I published it into our ERP software. I appreciate all the help and attached is the final product, if anyone cares to look.

I did never get the PO's to work right because I found out we have multiple PO's to a given operation and that created multiple records for the operation, so my logic for getting the "Prev,Curr,Next" operation didn't work. This is OK though because I was running out of room for the data and I had to have a big comment field. If it was dire for us I'm sure I could get it to work, or I actually I would have posted the question here :)

Anthony

Friday, March 9, 2012

Pl/SQL Beginner Problem, Selecting all records?

SET SERVEROUTPUT ON;

DECLARE
student_rec student%ROWTYPE;
BEGIN
SELECT *
INTO student_rec
FROM student
WHERE student_id = 156 ;
DBMS_OUTPUT.PUT_LINE ('Last Name : '|| student_rec.last_name || chr(10)||
'First Name : '|| student_rec.first_name || chr(10)||
'Phone Number : '|| student_rec.phone || chr(10)||
'Reg Date : '|| student_rec.registration_date);
EXCEPTION
WHEN no_data_found THEN
RAISE_APPLICATION_ERROR(-20001, 'Student with id = 156 is not in the Database');
WHEN others THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE || ' '|| substr(SQLERRM,1,80));
END;
.

In the above code it selects the information for the student with the id of 156, how do I change it so that it selects all students from the table instead of just the one?

Any help appreciated.just remove the condition tht where student id = 156:

SELECT *
INTO student_rec
FROM student

above script will select all the student in student and store it into the sudent_rec .

RAISE_APPLICATION_ERROR(-20001, 'Student with id = 156 is not in the Database');

when you want to raise the exeception just write it ther is no record in the table instad of student with id= 156 is not in the database.|||Hi,

Use a cursor & remove the Hard coded value 156 in the query.

Originally posted by iknownothing
SET SERVEROUTPUT ON;

DECLARE
student_rec student%ROWTYPE;
BEGIN
SELECT *
INTO student_rec
FROM student
WHERE student_id = 156 ;
DBMS_OUTPUT.PUT_LINE ('Last Name : '|| student_rec.last_name || chr(10)||
'First Name : '|| student_rec.first_name || chr(10)||
'Phone Number : '|| student_rec.phone || chr(10)||
'Reg Date : '|| student_rec.registration_date);
EXCEPTION
WHEN no_data_found THEN
RAISE_APPLICATION_ERROR(-20001, 'Student with id = 156 is not in the Database');
WHEN others THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE || ' '|| substr(SQLERRM,1,80));
END;
.

In the above code it selects the information for the student with the id of 156, how do I change it so that it selects all students from the table instead of just the one?

Any help appreciated.|||When I remove the WHERE statement, I get an error when I run it saying
"-1422 ORA-01422: exact fetch returns more than requested number of rows"|||Hi,

Use CURSOR to avoid this error. Because you can fetch only one row into the record type student_rec . When the value 156 is harcoded in the query , exactly one row is fetched into student_rec . So it works fine. But once you remove the hard coded value 156 from the query, all the records are fetched . Since the record type student_rec can accept only one value, it displays the error ORA-01422: exact fetch returns more than requested number of rows. To avoid this error & fetch all the records into student_rec, use a CURSOR.

Originally posted by iknownothing
When I remove the WHERE statement, I get an error when I run it saying
"-1422 ORA-01422: exact fetch returns more than requested number of rows"|||Its ok, fixed it! Thanks.|||As an aside from your question, you should get out of the habit of doing this:

EXCEPTION
WHEN no_data_found THEN
RAISE_APPLICATION_ERROR(-20001, 'Student with id = 156 is not in the Database');
WHEN others THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE || ' '|| substr(SQLERRM,1,80));
END;

All that does is potentially hide errors from the user and allow inconsistent partial transactions to be committed. It should be simply:

EXCEPTION
WHEN no_data_found THEN
RAISE_APPLICATION_ERROR(-20001, 'Student with id = 156 is not in the Database');
END;

Monday, February 20, 2012

Pivot Select

Hi,
I'm able to get Pivot to work but I'm having trouble limiting the record set. I want it to select only records from this FiscalYear. I have a table with a field called CurrentBudgetYear that I use as a control. So FiscalYear should equal CurrentBudgetYear but my results include all FiscalYears.

SELECT ProjNo, TaskCode, [1] AS P1, [2] AS P2, [3] AS P3, [4] AS P4, [5] AS P5, Devil AS P6, [7] AS P7, Music AS P8, [9] AS P9, [10] AS P10, [11] AS P11, [12] AS P12
FROM
(SELECT e.ProjNo, e.TaskCode, e.FiscalPeriod, e.ActualAmt
FROM tblActualExpend AS e
INNER JOIN tblBudgetConfig ON e.FiscalYear = tblBudgetConfig.CurrentBudgetYear
)p
PIVOT
(
SUM(ActualAmt)
FOR FiscalPeriod IN
( [1], [2], [3], [4], [5], Devil, [7], Music, [9], [10], [11], [12])
)AS pvt
ORDER BY ProjNo, TaskCode;

Thanks in advanced for any help.

It appears that in the derived table, you need a WHERE clause to constrain the data to a specific FiscalYear.

Something like:

WHERE e.FiscalYear >= '20060101' and e.FiscalYear < '20070101'

Or whatever dates demarc your Fiscal Year.

|||Thanks Arnie, I can see where that would work. I really want something more automated. Thats why I use the control table. This way all I have to do is change the value in one field in one table and all my queries are current.|||

As you noticed, If your 'control table' has rows all of your Fiscal Years, you retreive all Fiscal Years. The only way it would work without a WHERE clause is if the 'control table' has only one row of data for the current FiscalYear.

If you want only one fiscal Year, then you will have to specify which one. The query processor can't read your mind.

You could still 'automate' the process, for example, assuming your FiscalYear begins July 1:

WHERE e.FiscalYear >= cast( cast( ( year( getdate() ) - 1) AS char(4)) + '0701' AS datetime )
AND e.FiscalYear < cast( cast( ( year( getdate() )) AS char(4)) + '0701' AS datetime )

Will always derive the Fiscal year for the current date.

|||

Sorry to have bothered you. The pivot works exactly as I want. I was running it on test data that I took at the end of the last fiscal year so I was getting all of the fiscal periods. Becuase of that I was sure it was not working. I just updated my tables and I'm now getting the results I was expecting.

As an FYI, the 'control' table only has one record in it....the FiscalYear. For reporting purposes we can't cut over to the new fiscal year at the start of the year (atleast in the database) so we use this table to control all of that.

Cheers!

|||Not a problem!

PIVOT question

I have a basic table consisting of several thousand records. Im trying to generate a pivot query for a report. the table consists of records, each of which has a recieved date ( small date time ) and a tranactioncount ( int ) . Im looking to generate a PIVOT to show the show the month and year counts for the files recieved

ie

YEAR | JAN FEB MAR APR etc

2004 ! 2 34 67 43

2005 | 12 2 3 1

can anybody explain in laymans terms how to do this

Thank you in advance

are you using SQL 2000 or 2005 ?

If 2005, use the pivot function|||i am using sql2005, ive looked up the documentation on the PIVOT function but still am having diffaculity in applying it|||

To do this in 2000, check out my reply of this post:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=249991&SiteID=1

However, the PIVOT method in 2005 is better. What errors are you getting?

|||

You can do something like below using PIVOT operator:

select p.yr as Year, p.[1] as [Jan], p.[2] as [Feb], ....

from (select year(receivedate) as yr, month(receivedate) as mn, trancnt from tbl) as t

pivot (sum(t.trancnt) for t.mn in ([1], [2], [3], ...)) as p

|||

I am curious to know what are the practical uses of the Pivot function assuming you do not grant end users acces to your database.

On my side, I use the pivot function to pack more data in Reporting Services while avoiding the Matrix reports shortcomings, however it is very tedious to build. If you want if maitenance free. You have to break the rule of "NO dynamic SQL ever".

Any thoughts?

Philippe

|||Yes, the use cases of PIVOT operator is very restrictive right now. If you want to pivot on say multiple measures or aggregates then you have to use the traditional SQL approach of CASE expressions and GROUP BY in the query. The dynamic list generation for PIVOT operator is also something we have heard frequently from customers. A future version of SQL Server might provide additional enhancements, optimizations for PIVOT which will improve the usage & performance of the query. So if you find instances where you can achieve the result using PIVOT operator then use it instead of the CASE / GROUP BY approach. Hope this clarifies.

Pivot multiple columns

I have a table the records the results of three different tests that are graded on a scale of 1-7.The table looks something like this.

PersonIdTestATestBTestC

1454

2624

3556

4151

I would like to have a SQL statement that would pivot all this data into something like this

Test1234567

A1001110

B0100300

C1002010

Where the value for each number is a count of the number of people with that result.

The best solution that I have been able to come up with is to pivot each test and UNION ALL the results together.Is there a way to do this in a single statement?

(If this has already been covered I apologize, but I could not find the solution.)

Try:

use tempdb

go

Code Snippet

create table dbo.t1 (

PersonId int not null unique,

TestA int,

TestB int,

TestC int

)

go

insert into dbo.t1 values(1, 4, 5, 4)

insert into dbo.t1 values(2, 6, 2, 4)

insert into dbo.t1 values(3, 5, 5, 6)

insert into dbo.t1 values(4, 1, 5, 1)

go

;with unpvt

as

(

select

stuff(Test, 1, 4, '') as Test,

[Value]

from

dbo.t1

unpivot

(

[Value]

for [Test] in ([TestA], [TestB], [TestC])

) as unpvt

)

select

Test,[1], [2], [3], [4], [5], [6], [7]

from

unpvt

pivot

(

count([Value])

for [Value] in ([1], [2], [3], [4], [5], [6], [7])

) as pvt

order by

Test

go

drop table dbo.t1

go

AMB