Showing posts with label values. Show all posts
Showing posts with label values. Show all posts

Friday, March 30, 2012

How to exclude zero values when sorting?

I have a datagrid with a "sort" field I want to use to sort the rows in ascending order. However, I want values with a 0 or NULL value to be displayed last. I can't figure out how to do a sort (preferably in the SQL) that returns the empty values last. Is this possible?This isn't pretty but why don't you give it a go:
SELECT * FROM mytable WHERE myfield > 0 ORDER BY myfield ASC
UNION SELECT * FROM mytable WHERE myfield = 0

Regards
Fredr!k|||Unfortunately, this isn't valid syntax becuase ORDER BY must be at the end of the query. I get "Incorrect syntax near the keyword 'UNION'." when I try

SELECT * FROM Photo WHERE PhotoOrder > 0 ORDER BY PhotoOrder ASC UNION SELECT * FROM Photo WHERE PhotoOrder = 0|||To use the UNION operator in SQL Server all your Data types must be the same and the same order in both tables, but UNION is restrictive because it performs an Implicit DISTINCT by eliminating DUPLICATES. So if eliminating duplicates is not important try UNION ALL, if it still fails the it is INNER JOIN if both tables are equal or OUTER JOIN if they are not equal. Hope this helps.

Kind regards,
Gift Peddie|||I'm confused - how is this relevant to my question?|||I got what I wanted with
"ORDER BY IsNull(PhotoORDER, 1000)"

Unfortunately, zeroes will still sort first, but I can NULLify them on data entry|||You might try:


ORDER BY
CASE WHEN ISNULL(PhotoOrder,0) = 0 THEN 2 ELSE 1 END,
CASE WHEN ISNULL(PhotoOrder,0) <> 0 THEN PhotoOrder

Terri|||I was only replying your UNION error not your original post. I will try to be clear in the future.

Kind regards,
Gift Peddiesql

How to exclude duplicate records from totals

My column figures are correct in my report, but duplicate values are being added to the totals.

I am using:

Format(Sum(Fields!ACEG_Contribution.Value), "C")

This is not a matrix report. I am using tables so it only has table headers and table footers.

How can I fix this? Please advise a-sap.

Thanx in advance for any assistance you can provide,

gb

Hi Gerry-

Not completly certain where your duplication is coming from - as per your description. If duplicate values are present in your data, you would want to use the DISTINCT clause in your query to filter duplicates.

If you have groupings in your table, and want to subtotal rather than grandtotal, you can use the scope argument on the SUM function to filter per group i.e. Sum(Fields!Value, "Group1)".

If you want to display duplicates, bu only sum the non-duplicates, you would need to have a separate query which uses the DISTINCT caluse, then create an expression in your table footer which does sum of second dataset. i.e. SUM(Fields!Value, "DataSet2")

Hope that helps,

Thanks, Jon

Wednesday, March 28, 2012

How to ensure column uniqueness

Hi,
Coming from an Oracle background, I'm used to being able
to create a unique key on a column that allows many null
values, ie if a value exists it must be unique, otherwise
it can be null.
It appears as though SQL Server allows only 1 null value
in the same situation, ie create a unique constraint on a
column and once you try to insert a 2nd row with a null
value I get a constraint violation. [Thx to those that
replied to my last question on this]
I don't really want to write triggers testing for such
conditions. Is there some form of constraint that can do
this for me?
TIA,
SJTYour observations are correct. You can create a view conatining all rows but the NULL. Then create a
unique index (or possible a unique constraint) on that index.
--
Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=djq&as ugroup=microsoft.public.sqlserver
"SJT" <scott.taylor@.pwcs.com.au> wrote in message news:054601c36ad9$46dd1f90$a501280a@.phx.gbl...
> Hi,
> Coming from an Oracle background, I'm used to being able
> to create a unique key on a column that allows many null
> values, ie if a value exists it must be unique, otherwise
> it can be null.
> It appears as though SQL Server allows only 1 null value
> in the same situation, ie create a unique constraint on a
> column and once you try to insert a 2nd row with a null
> value I get a constraint violation. [Thx to those that
> replied to my last question on this]
> I don't really want to write triggers testing for such
> conditions. Is there some form of constraint that can do
> this for me?
>
> TIA,
> SJT|||You can use an indexed view to enforce uniqueness only for non-NULL values:
CREATE TABLE Sometable (keycol INTEGER PRIMARY KEY, colx INTEGER NULL)
GO
CREATE VIEW Sometable_Unique_Non_NULL
WITH SCHEMABINDING
AS SELECT colx FROM dbo.Sometable WHERE colx IS NOT NULL
GO
CREATE UNIQUE CLUSTERED INDEX uclcolx ON Sometable_Unique_Non_NULL (colx)
INSERT INTO Sometable VALUES (1,1)
INSERT INTO Sometable VALUES (2,NULL)
INSERT INTO Sometable VALUES (3,NULL)
--
David Portas
--
Please reply only to the newsgroup
--

Wednesday, March 21, 2012

How to eliminate the NULL field values

I am importing an Access .mdb file into MS SQL server, and empty fields where the default value is "", change into NULL. This is a problem when I re-export a result set and have to apply a procedure to clean these values. Is there a way to eliminate this? . . . . and what have I missed?Check 'allow nulls' and 'default value' settings in the access tables.|||and to solve for the export problem...

Use a query to export the table, and use
Select ISNULL(yourfield,"") AS FIELD1...sql

How to eliminate Space entries...?

Hey,
I have some field values entries in my database.. that are spaces like ' '. i wanna eliminate them.
When i use IS NOT NULL in query it only eliminates the rows with NULL values so how could i modify the query to eliminate the rows with spaces in the field value..

Thx in advance..where COALESCE(somecolumn,' ')<>' '|||Thank you very much sir..|||SELECT * FROM Table1 WHERE Col1 > ' '|||WHERE NULLIF(somecolumn,' ') IS NOT NULL

How to Eliminate Nodes with Null values?

I need to shred the xml data to retrieve BrandIDs based on the following business rules.

/**************************************************************************************************************************

(1) Not every instance of xml would contain BrandIDs node

(2) Ignore BrandIDs whenever its a descendant of AlternativeState

(3) We are interested in the data stored under MarketSize whenever the CurrentEvent node is MarketSize.

(4) We are interested in the data stored under OtherEvent whenever the CurrentEvent node is not MarketSize.

****************************************************************************************************************************/

While shredding the xml data, I have noticed that out of 200,000 xml rows there are only 1000 BrandIDs nodes that do actually have data in them (e.g. <BrandIDs> 123, 234</BrandIDs>. Others are just blank in the form of </BrandIDs>. I would like to modify XQuery given below so that I could filter out such rows where even though BrandIDs node exist but it has no scalar value for me to retrieve. From the sample query result given at the end you would notice that the third row is empty. I would like to avoid such rows in result set.

I am open to any suggestions here if anyone out there could come up with a better solution.

declare @.xml xml

set @.xml =

'

<State>

<StatsState>

<CurrentState>

<BrandIDs>2698741</BrandIDs>

</CurrentState>

</StatsState>

</State>

<State>

<StatsState>

<CurrentState>

<OtherEvents>

<BrandIDs>160603,160737</BrandIDs>

</OtherEvents>

<CurrentEvent>BrandShare</CurrentEvent>

</CurrentState>

</StatsState>

</State>

<State>

<StatsState>

<CurrentState>

<MarketSize>

<BrandIDs />

<AlternativeState>

<CurrentEvent>None</CurrentEvent>

<BrandIDs>25630,8956201</BrandIDs>

</AlternativeState>

<CompanyIDs />

</MarketSize>

<CurrentEvent>MarketSize</CurrentEvent>

</CurrentState>

</StatsState>

</State>

<State>

<StatsState>

<CurrentState>

<OtherEvents>

<BrandIDs>2001,2002,2003,2004,2005,2006</BrandIDs>

</OtherEvents>

<CurrentEvent>BrandShare</CurrentEvent>

<MarketSize>

<BrandIDs>40666,71788,201225</BrandIDs>

</MarketSize>

</CurrentState>

</StatsState>

</State>

'

SELECT

Element.Val.query(

'for $s in self::node()

where $s//*/BrandIDs[not(parent::AlternativeState)]

return

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) = "MarketSize")

then $s/StatsState/CurrentState/MarketSize/BrandIDs/text()

else (

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) != "MarketSize")

then $s/StatsState/CurrentState/OtherEvents/BrandIDs/text()

else $s//BrandIDs/text())

') AS BrandIDs

FROM @.xml.nodes('/State') AS Element(Val)

GO

BrandIDs

-

2698741

160603,160737

2001,2002,2003,2004,2005,2006

If an element is empty then it does not have any child nodes meaning you can check with e.g. BrandIDs[node()] for BrandIDs elements that are not empty.

So your query could be written as

Code Snippet

SELECT

Element.Val.query(

'for $s in self::node()

return

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) = "MarketSize")

then $s/StatsState/CurrentState/MarketSize/BrandIDs/text()

else (

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) != "MarketSize")

then $s/StatsState/CurrentState/OtherEvents/BrandIDs/text()

else $s//BrandIDs/text())

') AS BrandIDs

FROM @.xml.nodes('/State[.//*/BrandIDs[node() and not(parent::AlternativeState)]]') AS Element(Val)

|||

Hi marton,

Thanks once more for helping me out here. Your proposed solution does solve my problem. Is there any way that perhaps you could use the 'where' clause in FLWOR to apply the same condition? I actually have a requirement to use @.xml.nodes('/State'). I do have different set of FLWOR queries to read values for different nodes and for each the root node is always /State and I would need to combine all of them in one statement. So preferably I would like to keep the nodes clause pointing to root.

Hope you get my point.

thanks again

|||The problem is that the nodes methods shreds the xml variable into rows that you then query with the query method. So for the original example you got four rows in the result set as the nodes method yields four rows, independent of the query applied later to the each row. If you want to eliminate nodes to not yield rows at all then I think it as to be done with the nodes method.|||

Hi Martin,

Thanks for clarification. I understand your point.

I actually works with xml where each of the node goes to its own relational table and I wanted to have only one select statement where each xml row is read only once and I get all of the values for nodes by specifying any business rules within FLWOR there. Hence I hesitate to specify any specific node such as BrandIDs in nodes() because it wouldn't leave an option for me to work with other nodes. I think I would have to use function for each node and call them from my select statement.

Many thanks

Monday, March 19, 2012

How to dynamically change width?

Folks,

We have some reports that have optional columns. We have them working very nicely, with the column showing or hiding based on values in the report -- works great.

Except -- when the columns are present, the report spans onto two pages, when exported to PDF, in width. That's understandable, as there's a lot of extra data, and exactly what we want. However, when the columns are not present, we get empty pages instead, because the report doesn't automatically contract back onto the size that fits on one page.

Changing the report to a Matrix won't work, as the hidden columns on some of these come as sets of three, where each column in the three has different formatting (different widths, format codes, etc).

Thanks!

--randy

We have the same problem, columns thats hidden or not based och which parameters user used when the report is rendered. Everything is fine exept for when printing it... then the report is as wide as in design mode even if the columns is not visible, ending up with lots of blank pages. Is there anyway I can set width during runtime? It would be nice to be able to set the width to the sum of all shown column widths.

This is|||I'm also experiencing the same problem. The width of the column does not automatically adjust depending on the content of the report. Anyone who know's how to fix this? thanks.|||i have the same problem,somebody helps,and i also have a question how to dynamically set item'position.re|||

I too spend half a day trying to come up with a solution and found that no matter what is hidden, if the size of the table, list, matrix was outside the page width boudaries in design/layout mode the printed report would cross over.

I eventually came up with having two or more replica tables in the report that showed the different width columns in each table. For example, table one had financial information and based on a toggle the visbility would switch to table two that had the contact information, or the same information bar on eor two columns were different. The effect to the user is that a toggle can switch the between columns or column size without the boudaries being exceeded.

Rgds

Darrenh

|||I am having the same problem. Looks like MS should address this one.|||

Hi,

i have not faced such prob so far. but wat i feel is to make the width of all the columns to "0" and set the "Can Grow" property of the columns to "True" so that the columns expands horizontally based on the content it holds.

plz let me know if works fine.

Thanks.

|||I have experienced same problem also. Hope Microsoft addresses this.|||

But the CanGrow property does'nt seenm to have any effect.

I have dynamically changed the column widths in code according to a particular scenario.

|||

hi vaidyak,

"can grow" property should be set to true for all the textboxes of the row.

|||"CanGrow" doesn't seem to have any visible effect in this instance, even with all other textboxes in the row set to "CanGrow".

How to dynamically change width?

Folks,

We have some reports that have optional columns. We have them working very nicely, with the column showing or hiding based on values in the report -- works great.

Except -- when the columns are present, the report spans onto two pages, when exported to PDF, in width. That's understandable, as there's a lot of extra data, and exactly what we want. However, when the columns are not present, we get empty pages instead, because the report doesn't automatically contract back onto the size that fits on one page.

Changing the report to a Matrix won't work, as the hidden columns on some of these come as sets of three, where each column in the three has different formatting (different widths, format codes, etc).

Thanks!

--randy

We have the same problem, columns thats hidden or not based och which parameters user used when the report is rendered. Everything is fine exept for when printing it... then the report is as wide as in design mode even if the columns is not visible, ending up with lots of blank pages. Is there anyway I can set width during runtime? It would be nice to be able to set the width to the sum of all shown column widths.

This is|||I'm also experiencing the same problem. The width of the column does not automatically adjust depending on the content of the report. Anyone who know's how to fix this? thanks.|||i have the same problem,somebody helps,and i also have a question how to dynamically set item'position.re|||

I too spend half a day trying to come up with a solution and found that no matter what is hidden, if the size of the table, list, matrix was outside the page width boudaries in design/layout mode the printed report would cross over.

I eventually came up with having two or more replica tables in the report that showed the different width columns in each table. For example, table one had financial information and based on a toggle the visbility would switch to table two that had the contact information, or the same information bar on eor two columns were different. The effect to the user is that a toggle can switch the between columns or column size without the boudaries being exceeded.

Rgds

Darrenh

|||I am having the same problem. Looks like MS should address this one.|||

Hi,

i have not faced such prob so far. but wat i feel is to make the width of all the columns to "0" and set the "Can Grow" property of the columns to "True" so that the columns expands horizontally based on the content it holds.

plz let me know if works fine.

Thanks.

|||I have experienced same problem also. Hope Microsoft addresses this.|||

But the CanGrow property does'nt seenm to have any effect.

I have dynamically changed the column widths in code according to a particular scenario.

|||

hi vaidyak,

"can grow" property should be set to true for all the textboxes of the row.

|||"CanGrow" doesn't seem to have any visible effect in this instance, even with all other textboxes in the row set to "CanGrow".

How to dynamically change width?

Folks,

We have some reports that have optional columns. We have them working very nicely, with the column showing or hiding based on values in the report -- works great.

Except -- when the columns are present, the report spans onto two pages, when exported to PDF, in width. That's understandable, as there's a lot of extra data, and exactly what we want. However, when the columns are not present, we get empty pages instead, because the report doesn't automatically contract back onto the size that fits on one page.

Changing the report to a Matrix won't work, as the hidden columns on some of these come as sets of three, where each column in the three has different formatting (different widths, format codes, etc).

Thanks!

--randy

We have the same problem, columns thats hidden or not based och which parameters user used when the report is rendered. Everything is fine exept for when printing it... then the report is as wide as in design mode even if the columns is not visible, ending up with lots of blank pages. Is there anyway I can set width during runtime? It would be nice to be able to set the width to the sum of all shown column widths.

This is|||I'm also experiencing the same problem. The width of the column does not automatically adjust depending on the content of the report. Anyone who know's how to fix this? thanks.|||i have the same problem,somebody helps,and i also have a question how to dynamically set item'position.re|||

I too spend half a day trying to come up with a solution and found that no matter what is hidden, if the size of the table, list, matrix was outside the page width boudaries in design/layout mode the printed report would cross over.

I eventually came up with having two or more replica tables in the report that showed the different width columns in each table. For example, table one had financial information and based on a toggle the visbility would switch to table two that had the contact information, or the same information bar on eor two columns were different. The effect to the user is that a toggle can switch the between columns or column size without the boudaries being exceeded.

Rgds

Darrenh

|||I am having the same problem. Looks like MS should address this one.|||

Hi,

i have not faced such prob so far. but wat i feel is to make the width of all the columns to "0" and set the "Can Grow" property of the columns to "True" so that the columns expands horizontally based on the content it holds.

plz let me know if works fine.

Thanks.

|||I have experienced same problem also. Hope Microsoft addresses this.|||

But the CanGrow property does'nt seenm to have any effect.

I have dynamically changed the column widths in code according to a particular scenario.

|||

hi vaidyak,

"can grow" property should be set to true for all the textboxes of the row.

|||"CanGrow" doesn't seem to have any visible effect in this instance, even with all other textboxes in the row set to "CanGrow".

How to dynamically change width?

Folks,

We have some reports that have optional columns. We have them working very nicely, with the column showing or hiding based on values in the report -- works great.

Except -- when the columns are present, the report spans onto two pages, when exported to PDF, in width. That's understandable, as there's a lot of extra data, and exactly what we want. However, when the columns are not present, we get empty pages instead, because the report doesn't automatically contract back onto the size that fits on one page.

Changing the report to a Matrix won't work, as the hidden columns on some of these come as sets of three, where each column in the three has different formatting (different widths, format codes, etc).

Thanks!

--randy

We have the same problem, columns thats hidden or not based och which parameters user used when the report is rendered. Everything is fine exept for when printing it... then the report is as wide as in design mode even if the columns is not visible, ending up with lots of blank pages. Is there anyway I can set width during runtime? It would be nice to be able to set the width to the sum of all shown column widths.

This is|||I'm also experiencing the same problem. The width of the column does not automatically adjust depending on the content of the report. Anyone who know's how to fix this? thanks.|||i have the same problem,somebody helps,and i also have a question how to dynamically set item'position.re|||

I too spend half a day trying to come up with a solution and found that no matter what is hidden, if the size of the table, list, matrix was outside the page width boudaries in design/layout mode the printed report would cross over.

I eventually came up with having two or more replica tables in the report that showed the different width columns in each table. For example, table one had financial information and based on a toggle the visbility would switch to table two that had the contact information, or the same information bar on eor two columns were different. The effect to the user is that a toggle can switch the between columns or column size without the boudaries being exceeded.

Rgds

Darrenh

|||I am having the same problem. Looks like MS should address this one.|||

Hi,

i have not faced such prob so far. but wat i feel is to make the width of all the columns to "0" and set the "Can Grow" property of the columns to "True" so that the columns expands horizontally based on the content it holds.

plz let me know if works fine.

Thanks.

|||I have experienced same problem also. Hope Microsoft addresses this.|||

But the CanGrow property does'nt seenm to have any effect.

I have dynamically changed the column widths in code according to a particular scenario.

|||

hi vaidyak,

"can grow" property should be set to true for all the textboxes of the row.

|||"CanGrow" doesn't seem to have any visible effect in this instance, even with all other textboxes in the row set to "CanGrow".

Wednesday, March 7, 2012

How to do this?

I know how to use IN with WHERE clause but it does the OR on all values in the subquery. The question is how to make it match against all values returned?

ex:

SELECT UserID FROM UserCars WHERE CarID IN (10,20,30)

would return user ids of all users that have a either car 10, 20 OR 30

How to write simple query to get users that have cars 10, 20 AND 30

thanks,where CarID between 10 and 30

otherwise

where CarID = 10 and CarID = 20 and CarID = 30 and CarID = 10000001|||hmm, so there is really no other statement like IN that would do AND instead of OR on subquery?

i tried using ALL but that didnt work :/|||select u.UserID
from Users u
where exists(select 'x' from UserCars uc1 where u.UserID=uc1.UserID and uc1.CarID=10)
and exists(select 'x' from UserCars uc2 where u.UserID=uc1.UserID and uc1.CarID=20)
and exists(select 'x' from UserCars uc2 where u.UserID=uc1.UserID and uc1.CarID=30)

OR

select UserID
from UserCars
where CarID in (10,20,30)
group by UserID
having count('x')=3

How to do this in Stored Procedure

Hi,
I want to do something like this is my SP. If ' ' emplty string parameters are sent, I want the SP to use certain default values and use them in the query. code below is a rough idea..


CREATE PROCEDURE CabsSchedule_ViewLatest
(
@.SiteCode smallint,
@.YearMonth int
)
AS
IF @.YearMonth = ' ' OR @.SiteCode = ' '
BEGIN
@.YearMonth = DateTime.Now()
@.SiteCode = 'GN'
END

SELECT JulianDate, CalendarDay, BillPeriod, WorkDay,CalDayBillRcvd, Remarks
FROM CabsSchedule WHERE YearMonth = @.YearMonth AND SiteCode = @.SiteCode

GO


CREATE PROCEDURE CabsSchedule_ViewLatest
(
@.SiteCode smallint = NULL,
@.YearMonth int = NULL
)
AS

SET NOCOUNT ON

IF @.YearMonth IS NULL OR @.SiteCode IS NULL
BEGIN
SET @.YearMonth = Getdate()
SET @.SiteCode = 'GN'
END

SELECT...

SET NOCOUNT OFF

hth|||You have numeric parameters, so checking for ' ' is not meaningful. Try using default values for the SP:


CREATE PROCEDURE CabsSchedule_ViewLatest

(
@.SiteCode smallint = -1,
@.YearMonth int = -1
)

This presumes -1 is a reasonable default (probably not)|||Hi Dinakar,
Thanks for the reply. I want to assign the latest YearMonth available in the my table to the @.YearMonth field. The format of YearMonth would be 200408 representing Year=2004 and Month=08 respectively, could this formatting be done using T-SQL functions??

Thanks,|||yeah there are some datefunctions available in SQL Server. check out BOL. in your case you wud prbly need Month(Getdate()).

hth|||REPLACE(CONVERT(nvarchar(10),DATEPART(yy,GetDate())) + Str(DATEPART(mm,GetDate()),2),' ','0')

You could do it more easily using Month() and Year() if you always want to use todays date.|||Douglas and Dinakar,
Thanks for the replies but, What I'm really looking for is the the latest YearMonth value available in the Table field YearMonth. I need this b'cos I need to extract all the rows corresponding to the YearMonth field as all the rows in a particular schedule could be classified by this field. What this means is for the Year 2004 and Month 08 I've got the number of rows corresponding to the number of working days in month represented by 08.
So, what I need is to pull all the rows with latest YearMonth field. Any ideas on how to pull the latest group of rows classified by the YearMonth field??

Thanks|||SELECT * FROM mytable WHERE YearMonth=(SELECT MAX(YearMonth) FROM myTable)|||Thanks for the reply Doug. I'm wiht another problem now. What I'm trying to do is to pass values from a SP as alias. ie. if I come across a value -1 in one of my rows in Column Called WorkDay, Then I want to pass string 'HOLIDAY' instead. I've been playing around with the CAST and CASE statements in my SP but couldn't make them to work. Any help with this??

The check syntax throws an error saying that the syntax is incorrect near '='.

Thanks,


CREATE PROCEDURE CabsSchedule_ViewLatest
(
@.SiteCode smallint = 0,
@.YearMonth int = NULL
)
AS
IF @.YearMonth IS NULL OR @.YearMonth = 0
BEGIN
SET @.YearMonth = (SELECT MAX(YearMonth) FROM CabsSchedule)
END

SELECT CAST(BillPeriod AS VARCHAR(7)) AS NewBillPeriod=
CASE NewBillBeriod
WHEN 32 THEN 'NB'
WHEN 33 THEN 'HOLIDAY'
ELSE BillPeriod
END,
JulianDate, CalendarDay, WorkDay, CalDayBillRcvd, Remarks
FROM CabsSchedule WHERE YearMonth = @.YearMonth AND SiteCode = @.SiteCode
GO

|||What is NewBillPeriod?


SELECT
CASE NewBillBeriod
WHEN 32 THEN 'NB'
WHEN 33 THEN 'HOLIDAY'
ELSE BillPeriod
END as SomeOtherFieldName,
JulianDate, CalendarDay, WorkDay, CalDayBillRcvd, Remarks
FROM CabsSchedule WHERE YearMonth = @.YearMonth AND SiteCode = @.SiteCode

BTW, What you are doing (overloading values to mean something "special" other than what they normally mean) is a bad thing...|||Thanks Doug,
But I really neeed to use this for storing optimal data in the table. I mean just to store just 2 different kinds of strings that too which can occur only a cpl of times, I thought of having alias values. Yes it does mean that a value being stored into the table means something special, but I thought that I'm better of storing special values instead of storing strings which have few occurances.
Also, before getting to your solution, I tried this and got it working but was having a few problems accessing it from my program. The error said that a string could not be implicitly converted into a smallint. Why is it saying that??

Thanks,|||It is saying that because you are using a string where the system expects a smallint. If you have a smallint field, it cannot store "FRED" or even "123", but can store 123. A string is a string, and a smallint is a smallint, and if you are converting from one to the other, you need to do it explicitly, using a cast.|||Doug,
I had tried using CAST on the fields in which I wanted to have alias values. I did domething like this but it didn't work and was saying that there was some incorrect syntax at the '=' on the CAST line in the below code. Could this be corrected to get what I'm looking for?? Also, the error says that there is not function called VARCHAR, but this is not a function.
What is going wrong here?


CREATE PROCEDURE CabsSchedule_ViewSchedule
(
@.SiteCode smallint = 0,
@.YearMonth int = NULL
)
AS
IF @.YearMonth IS NULL OR @.YearMonth = 0
BEGIN
SET @.YearMonth = (SELECT MAX(YearMonth) FROM CabsSchedule)
END

SELECT CAST(BillPeriod AS VARCHAR(7)) =
CASE
WHEN BillPeriod = '32' THEN 'NB'
WHEN BillPeriod = '33' THEN 'Holiday'
ELSE BillPeriod
END,
CAST(WorkDay AS VARCHAR(7))=
CASE
WHEN WorkDay = '-1' THEN ''
WHEN WorkDay = '0' THEN 'Holiday'
ELSE WorkDay
END,
JulianDate, CalendarDay, CalDayBillRcvd, Remarks
FROMCabsSchedule
WHERE YearMonth = @.YearMonth AND SiteCode = @.SiteCode
GO

Thanks|||In a previous post, I gave an example of how to do what you wish (I added a CONVERT call here, since that might be required, depending upon your data):


SELECT
CASE NewBillBeriod
WHEN 32 THEN 'NB'
WHEN 33 THEN 'HOLIDAY'
ELSE CONVERT(nvarchar(20),BillPeriod)
END as SomeOtherFieldName,
JulianDate, CalendarDay, WorkDay, CalDayBillRcvd, Remarks
FROM CabsSchedule WHERE YearMonth = @.YearMonth AND SiteCode = @.SiteCode

The syntax you are continuing to try to use will NEVER work.|||Thanks Doug,
The above change in my SP worked, but I was wondering why it wouldn't work if I CAST the BillPeriod in the CASE statement itself. Since, I CAST it to VarChar, the options for assignment it would have would still be the same and I did not care about CASTING the field BillPeriod in the ELSE statement (as you did) as smallint to varchar and Vice versa conversion needs no explicit CASTING(From what I read in BOL). What am I missing in my learning here?

Thanks again!

Friday, February 24, 2012

How to do Running Total on a field

I am creating a Summary report and on one of the fields "Resume Exists" has values of Yes or No. I am trying to do a summary by BU on this field to say how many resumes don't exist. So I would like it to total how many No's are in the Resume Exists field.

I was thinking of having the field on the detail row, but hide it, then do a summary on the footer.

I have not been very successful and was wondering if anyone has done this and if you can provide me an example. Any help would be greatly appreciated.

If you just want to get a total per group (BU), you don't need to use running total. Just add an aggregate on the group level like this: =Sum(IIF(Fields!ResumeExists.Value="No", 1, 0)). However, if you want to have a running total in the detail row to show how many No's you've encountered so far in each BU, you need to use the running value function: =RunningValue(IIF(Fields!ResumeExists.Value="No", 1, 0), Sum, "BUGroup").

Sunday, February 19, 2012

How to do a Join Using Foreign Keys in Stored in a Database Column?

I have a database column that stores a comma delimited list of foreign
keys. Would someone show me how to do a join using the values from a
list stored within a record?

For example, a record in tbl_cds.genre_id might have a value of "2,
5, 6" corresponding to genre_ids 2 , 5 and 6. I want to join
tbl_cds.genre_id to tbl_genre.genre_id using the values in that data
field.

It seems I need a loop like this:
SELECT * FROM tbl_cds
WHERE
Begin Loop
tbl_cds.genre_id[i] = tbl_genre.genre_id
End Loop.

Would someone give me the correct syntax?
Is there an alternative method that would create less overhead?

Sorry for such a novice post.On 17 Apr 2007 14:55:36 -0700, Chris wrote:

Quote:

Originally Posted by

>I have a database column that stores a comma delimited list of foreign
>keys. Would someone show me how to do a join using the values from a
>list stored within a record?
>
>For example, a record in tbl_cds.genre_id might have a value of "2,
>5, 6" corresponding to genre_ids 2 , 5 and 6. I want to join
>tbl_cds.genre_id to tbl_genre.genre_id using the values in that data
>field.
>
>It seems I need a loop like this:
>SELECT * FROM tbl_cds
>WHERE
>Begin Loop
>tbl_cds.genre_id[i] = tbl_genre.genre_id
>End Loop.
>
>Would someone give me the correct syntax?
>Is there an alternative method that would create less overhead?
>
>Sorry for such a novice post.


Hi Chris,

You can't. And that's because the database design volates one of the
basic principles of databases - you store a single value in a column.

If a CD can belong to three genres, you'll have to add a table like
this:

CREATE TABLE CDGenres
(CD_ID int NOT NULL,
Genre_ID int NOT NULL,
PRIMARY KEY (CD_ID, Genre_ID),
FOREIGN KEY (CD_ID) REFERENCES tbl_cds(CD_ID),
FOREIGN KEY (Genre_ID) REFERENCES Genres(Genre_ID)
);

If you don't have a master table of all genres, then you can leave out
the last foreign key constraint.

--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||Chris (christopher.b.lewis@.gmail.com) writes:

Quote:

Originally Posted by

I have a database column that stores a comma delimited list of foreign
keys. Would someone show me how to do a join using the values from a
list stored within a record?
>
For example, a record in tbl_cds.genre_id might have a value of "2,
5, 6" corresponding to genre_ids 2 , 5 and 6. I want to join
tbl_cds.genre_id to tbl_genre.genre_id using the values in that data
field.
>
It seems I need a loop like this:
SELECT * FROM tbl_cds
WHERE
Begin Loop
tbl_cds.genre_id[i] = tbl_genre.genre_id
End Loop.
>
Would someone give me the correct syntax?
Is there an alternative method that would create less overhead?


As Hugo said, you are in desperate need of a redesign.

On SQL 2005 you can nevertheless do:

SELECT *
FROM tbl_cds c
OUTER APPLY list_to_table(c.genre_id) l
JOIN tbl_genre g ON l.num = g.genre_id

where list_to_table is a table-valued function that unpacks the
comma-separated list into a table. See
http://www.sommarskog.se/arrays-in-sql.html for examples of such functions.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx