Sunday, March 25, 2012
CAN'T SOLVE SELECT GROUPING WITH MAX FUNCTION
ACCOUNT CONTACT DATE
account A CILXFA000HJ6 4/6/2005 16:05
account A C15467XXXXXX 7/27/2005 12:22
account B C20002XXXXXX 2/15/2005 18:25
account B C12225XXXXXX 12/14/2005 20:10
The RESULT should be this;
account A C15467XXXXXX 7/27/2005 12:22
account B C12225XXXXXX 12/14/2005 20:10
I tried using MAX function to get the LAST modified date display one
single record with account, contact and LAST modified date or last date
fields but the problem is that I can't use it to select out the right
contact because it is not designed to pick the last record? What are
other possible simple solutions. PS. The listing is already sorted by
date.
Rodselect account, contact, date
from yourtable t1
where date = (select max(date)
from yourtable
where account=t1.account
)
rlueneberg@.gmail.com wrote:
> Here is the scenario
> ACCOUNT CONTACT DATE
> account A CILXFA000HJ6 4/6/2005 16:05
> account A C15467XXXXXX 7/27/2005 12:22
> account B C20002XXXXXX 2/15/2005 18:25
> account B C12225XXXXXX 12/14/2005 20:10
> The RESULT should be this;
> account A C15467XXXXXX 7/27/2005 12:22
> account B C12225XXXXXX 12/14/2005 20:10
> I tried using MAX function to get the LAST modified date display one
> single record with account, contact and LAST modified date or last date
> fields but the problem is that I can't use it to select out the right
> contact because it is not designed to pick the last record? What are
> other possible simple solutions. PS. The listing is already sorted by
> date.
>
> Rod
>|||Alternatively:
select t1.account, t1.contact, t2.maxdate from yourtable t1
INNER JOIN
(select account, MAX(date) as "maxdate" from yourtable group by account) t2
ON t1.account=t2.account
"rlueneberg@.gmail.com" wrote:
> Here is the scenario
> ACCOUNT CONTACT DATE
> account A CILXFA000HJ6 4/6/2005 16:05
> account A C15467XXXXXX 7/27/2005 12:22
> account B C20002XXXXXX 2/15/2005 18:25
> account B C12225XXXXXX 12/14/2005 20:10
> The RESULT should be this;
> account A C15467XXXXXX 7/27/2005 12:22
> account B C12225XXXXXX 12/14/2005 20:10
> I tried using MAX function to get the LAST modified date display one
> single record with account, contact and LAST modified date or last date
> fields but the problem is that I can't use it to select out the right
> contact because it is not designed to pick the last record? What are
> other possible simple solutions. PS. The listing is already sorted by
> date.
>
> Rod
>|||Oops. This work better:
select t1.account, t1.contact, t2.maxdate from yourtable t1
INNER JOIN
(select account, MAX(date) as "maxdate" from yourtable group by account) t2
ON t1.date=t2.maxdate
"Mark Williams" wrote:
> Alternatively:
> select t1.account, t1.contact, t2.maxdate from yourtable t1
> INNER JOIN
> (select account, MAX(date) as "maxdate" from yourtable group by account) t
2
> ON t1.account=t2.account
>
> --
>
> "rlueneberg@.gmail.com" wrote:
>|||Mark, you need to specify both columns in your join clause:
select t1.account, t1.contact, t2.maxdate from yourtable t1
INNER JOIN
(select account, MAX(date) as "maxdate" from yourtable group by account) t2
ON t1.account = t2.account and t1.date=t2.maxdate
Joe
"Mark Williams" wrote:
> Oops. This work better:
> select t1.account, t1.contact, t2.maxdate from yourtable t1
> INNER JOIN
> (select account, MAX(date) as "maxdate" from yourtable group by account) t
2
> ON t1.date=t2.maxdate
>
> "Mark Williams" wrote:
>|||Thanks Joe. I thought about it for a few minutes, and realized that if two
accounts had the same max date value, my query would produce the wrong
results.
"Joe from WI" wrote:
> Mark, you need to specify both columns in your join clause:
> select t1.account, t1.contact, t2.maxdate from yourtable t1
> INNER JOIN
> (select account, MAX(date) as "maxdate" from yourtable group by account) t
2
> ON t1.account = t2.account and t1.date=t2.maxdate
> Joe
> "Mark Williams" wrote:
>|||That was exactly what I was looking. It took a quite some time to run
though, but it does the job precisely. I will test the other
suggestions and see how it goes.
Thank you
Rod|||Using the suggested script I found that there are some contacts with
exact same create date and time, including seconds. This is because
they were eletronically imported. This leads to another scenario. I
need to assign at least one contact as a primary contact. In this case,
how can I pick the first one or the last one? If this is not possible,
then how can I randomly pick just one record of each grouped result. PS
There is no autoincrement or sequential column.
For example:
account C CILXFA000HJ6 4/6/2005 16:05
account C CILXFA000333 4/6/2005 16:05
account D C20002XXXXXX 2/15/2005 18:25
account D C50902XXXXXX 2/15/2005 18:25
account D C50008XXXXXX 2/15/2005 18:25
Thanks
Rod
Thursday, March 22, 2012
Cant seem to modify a SQL Server 2000 Table Valued Function in SQL Server Management Studi
I cant seem to modify a SQL Server 2000 Table Valued Function through
SQL Server Management Studio (2005)
Has anyone else experienced this issue?
DicksterAny errors?
For me it works, make sure that the database is set up compatibility level
90
<grd@.renre.com> wrote in message
news:1160058691.080724.39850@.k70g2000cwa.googlegroups.com...
> Hi
> I cant seem to modify a SQL Server 2000 Table Valued Function through
> SQL Server Management Studio (2005)
> Has anyone else experienced this issue?
> Dickster
>|||grd@.renre.com wrote:
> Hi
> I cant seem to modify a SQL Server 2000 Table Valued Function through
> SQL Server Management Studio (2005)
> Has anyone else experienced this issue?
> Dickster
>
What do you mean by "can't seem to modify" ? If you execute the DDL
script (i.e. the "ALTER FUNCTION" or "CREATE FUNCTION" script), what
happens?
Tracy McKibben
MCDBA
http://www.realsqlguy.com|||> What do you mean by "can't seem to modify" ? If you execute the DDL
> script (i.e. the "ALTER FUNCTION" or "CREATE FUNCTION" script), what
> happens?
Tracy
I get the following error message
----
Property QuotedIdentifierStatus is not available for
UserDefinedFunciton '[bdo].[SplitCsvList]'. This property may not exist
for this object, or may not be retrievable due to insufficient access
rights (Microsoft.SqlServer.Smo)
----
NB: I am logged in as 'sa'
Dickster|||> What do you mean by "can't seem to modify" ? If you execute the DDL
> script (i.e. the "ALTER FUNCTION" or "CREATE FUNCTION" script), what
> happens?
>
Tracy
I right Mouse click on the Table Valued Function & Select 'Modify'
I get the following error message
----
Property QuotedIdentifierStatus is not available for
UserDefinedFunciton '[bdo].[SplitCsvList]'. This property may not exist
for this object, or may not be retrievable due to insufficient access
rights (Microsoft.SqlServer.Smo)
----
NB: I am logged in as 'sa'
Dickster|||Try without the GUI. ALTER FUNCTION. That would lead you to whether the problem is in the GUI or
server level. The GUI, however, will just pull out the source code from the system tables and slap
an ALTER FUNCITON around it and show that in a query window. So the problem seem to be getting at
the source code from SQL Servers meta-data views.
I ran a Profiler trace when right-clicking and selection Modify on a single statement table valued
function. Below seem to be the key parts. You can tru to modify the relevant parts in there and run
from a query window to see if that same error is returned.
Perhaps it is a compatibility level issue for the database?
SELECT
SCHEMA_NAME(udf.schema_id) AS [Schema],
udf.name AS [Name]
FROM
sys.all_objects AS udf
WHERE
(udf.type in ('TF', 'FN', 'IF', 'FS', 'FT'))and(udf.name=N'f' and SCHEMA_NAME(udf.schema_id)=N'dbo')
SELECT
udf.name AS [Name],
udf.object_id AS [ID],
udf.create_date AS [CreateDate],
udf.modify_date AS [DateLastModified],
SCHEMA_NAME(udf.schema_id) AS [Schema],
CAST(
case
when udf.is_ms_shipped = 1 then 1
when (
select
major_id
from
sys.extended_properties
where
major_id = udf.object_id and
minor_id = 0 and
class = 1 and
name = N'microsoft_database_tools_support')
is not null then 1
else 0
end
AS bit) AS [IsSystemObject],
usrt.name AS [DataType],
sret_param.name AS [DataTypeSchema],
ISNULL(baset.name, N'') AS [SystemType],
CAST(CASE WHEN baset.name IN (N'nchar', N'nvarchar') AND ret_param.max_length <> -1 THEN
ret_param.max_length/2 ELSE ret_param.max_length END AS int) AS [Length],
CAST(ret_param.precision AS int) AS [NumericPrecision],
CAST(ret_param.scale AS int) AS [NumericScale],
ISNULL(xscret_param.name, N'') AS [XmlSchemaNamespace],
ISNULL(s2ret_param.name, N'') AS [XmlSchemaNamespaceSchema],
ISNULL( (case ret_param.is_xml_document when 1 then 2 else 1 end), 0) AS [XmlDocumentConstraint],
CAST(OBJECTPROPERTYEX(udf.object_id,N'ExecIsAnsiNullsOn') AS bit) AS [AnsiNullsStatus],
CAST(OBJECTPROPERTYEX(udf.object_id, N'IsSchemaBound') AS bit) AS [IsSchemaBound],
CAST(CASE WHEN ISNULL(smudf.definition, ssmudf.definition) IS NULL THEN 1 ELSE 0 END AS bit) AS
[IsEncrypted],
case when amudf.object_id is null then N'' else asmbludf.name end AS [AssemblyName],
case when amudf.object_id is null then N'' else amudf.assembly_class end AS [ClassName],
case when amudf.object_id is null then N'' else amudf.assembly_method end AS [MethodName],
CAST(case when amudf.object_id is null then CAST(smudf.null_on_null_input AS bit) else
amudf.null_on_null_input end AS bit) AS [ReturnsNullOnNullInput],
case when amudf.object_id is null then case isnull(smudf.execute_as_principal_id, -1) when -1 then 1
when -2 then 2 else 3 end else case isnull(amudf.execute_as_principal_id, -1) when -1 then 1 when -2
then 2 else 3 end end
AS [ExecutionContext],
case when amudf.object_id is null then ISNULL(user_name(smudf.execute_as_principal_id),N'') else
user_name(amudf.execute_as_principal_id) end AS [ExecutionContextPrincipal],
CAST(OBJECTPROPERTYEX(udf.object_id, N'IsDeterministic') AS bit) AS [IsDeterministic],
(case when 'FN' = udf.type then 1 when 'FS' = udf.type then 1 when 'IF' = udf.type then 3 when 'TF'
= udf.type then 2 when 'FT' = udf.type then 2 else 0 end) AS [FunctionType],
CASE WHEN udf.type IN ('FN','IF','TF') THEN 1 WHEN udf.type IN ('FS','FT') THEN 2 ELSE 1 END AS
[ImplementationType],
CAST(OBJECTPROPERTYEX(udf.object_id, N'IsQuotedIdentOn') AS bit) AS [QuotedIdentifierStatus],
ret_param.name AS [TableVariableName],
ISNULL(smudf.definition, ssmudf.definition) AS [Definition]
FROM
sys.all_objects AS udf
LEFT OUTER JOIN sys.all_parameters AS ret_param ON ret_param.object_id = udf.object_id and
ret_param.is_output = 1
LEFT OUTER JOIN sys.types AS usrt ON usrt.user_type_id = ret_param.user_type_id
LEFT OUTER JOIN sys.schemas AS sret_param ON sret_param.schema_id = usrt.schema_id
LEFT OUTER JOIN sys.types AS baset ON baset.user_type_id = ret_param.system_type_id and
baset.user_type_id = baset.system_type_id
LEFT OUTER JOIN sys.xml_schema_collections AS xscret_param ON xscret_param.xml_collection_id =ret_param.xml_collection_id
LEFT OUTER JOIN sys.schemas AS s2ret_param ON s2ret_param.schema_id = xscret_param.schema_id
LEFT OUTER JOIN sys.sql_modules AS smudf ON smudf.object_id = udf.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmudf ON ssmudf.object_id = udf.object_id
LEFT OUTER JOIN sys.assembly_modules AS amudf ON amudf.object_id = udf.object_id
LEFT OUTER JOIN sys.assemblies AS asmbludf ON asmbludf.assembly_id = amudf.assembly_id
WHERE
(udf.type in ('TF', 'FN', 'IF', 'FS', 'FT'))and(udf.name=N'f' and SCHEMA_NAME(udf.schema_id)=N'dbo')
SELECT
NULL AS [Text],
ISNULL(smudf.definition, ssmudf.definition) AS [Definition]
FROM
sys.all_objects AS udf
LEFT OUTER JOIN sys.sql_modules AS smudf ON smudf.object_id = udf.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmudf ON ssmudf.object_id = udf.object_id
WHERE
(udf.type in ('TF', 'FN', 'IF', 'FS', 'FT'))and(udf.name=N'f' and SCHEMA_NAME(udf.schema_id)=N'dbo')
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
<grd@.renre.com> wrote in message news:1160069137.082636.156350@.k70g2000cwa.googlegroups.com...
>> What do you mean by "can't seem to modify" ? If you execute the DDL
>> script (i.e. the "ALTER FUNCTION" or "CREATE FUNCTION" script), what
>> happens?
>
> Tracy
> I right Mouse click on the Table Valued Function & Select 'Modify'
> I get the following error message
> ----
> Property QuotedIdentifierStatus is not available for
> UserDefinedFunciton '[bdo].[SplitCsvList]'. This property may not exist
> for this object, or may not be retrievable due to insufficient access
> rights (Microsoft.SqlServer.Smo)
> ----
> NB: I am logged in as 'sa'
> Dickster
>|||grd@.renre.com wrote:
>> What do you mean by "can't seem to modify" ? If you execute the DDL
>> script (i.e. the "ALTER FUNCTION" or "CREATE FUNCTION" script), what
>> happens?
> Tracy
> I get the following error message
> ----
> Property QuotedIdentifierStatus is not available for
> UserDefinedFunciton '[bdo].[SplitCsvList]'. This property may not exist
> for this object, or may not be retrievable due to insufficient access
> rights (Microsoft.SqlServer.Smo)
> ----
> NB: I am logged in as 'sa'
> Dickster
>
This is a known bug...
https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=126099
Tracy McKibben
MCDBA
http://www.realsqlguy.com|||Thanks for your reply Tracy and to all others who replied.
Dickster
Tuesday, March 20, 2012
Can''t see function for code added in Report Properties
I put a function in the code section of Report Properties. I went to add an expression and can't find the function. I type =code. and did not see the function I created in the list.
Here's my code below:
Code Snippet
Public Function ConvertToStartDate(ByVal StartDate As String) As DateTime
Select Case StartDate
Case "Today"
Return DateTime.Today
Case "Yesterday"
Return DateTime.Today.AddDays(-1)
Case "30DaysOut"
Return DateTime.Today.AddDays(+30)
Case "2DaysPrior"
Return DateTime.Today.AddDays(-2)
' Additional cases
Case Else
Throw New ArgumentException("Unknown argument, " & StartDate, "StartDate")
End Select
End Function
I should be able to put in expression =code.ConvertToStartDate.StartDate("Today"), but that does not work. I get a red squiggly line under StartDate.
Thanks for your help,
Iris
from your code snippet up above, you would use:
=Code.ConvertToStartDate("Today")
I havent had the intellisense work on custom function code.
BobP
|||Works like a charm....Thanks!
Iris
Can''t see function for code added in Report Properties
I put a function in the code section of Report Properties. I went to add an expression and can't find the function. I type =code. and did not see the function I created in the list.
Here's my code below:
Code Snippet
Public Function ConvertToStartDate(ByVal StartDate As String) As DateTime
Select Case StartDate
Case "Today"
Return DateTime.Today
Case "Yesterday"
Return DateTime.Today.AddDays(-1)
Case "30DaysOut"
Return DateTime.Today.AddDays(+30)
Case "2DaysPrior"
Return DateTime.Today.AddDays(-2)
' Additional cases
Case Else
Throw New ArgumentException("Unknown argument, " & StartDate, "StartDate")
End Select
End Function
I should be able to put in expression =code.ConvertToStartDate.StartDate("Today"), but that does not work. I get a red squiggly line under StartDate.
Thanks for your help,
Iris
from your code snippet up above, you would use:
=Code.ConvertToStartDate("Today")
I havent had the intellisense work on custom function code.
BobP
|||Works like a charm....Thanks!
Iris
Can''t see function for code added in Report Properties
I put a function in the code section of Report Properties. I went to add an expression and can't find the function. I type =code. and did not see the function I created in the list.
Here's my code below:
Code Snippet
Public Function ConvertToStartDate(ByVal StartDate As String) As DateTime
Select Case StartDate
Case "Today"
Return DateTime.Today
Case "Yesterday"
Return DateTime.Today.AddDays(-1)
Case "30DaysOut"
Return DateTime.Today.AddDays(+30)
Case "2DaysPrior"
Return DateTime.Today.AddDays(-2)
' Additional cases
Case Else
Throw New ArgumentException("Unknown argument, " & StartDate, "StartDate")
End Select
End Function
I should be able to put in expression =code.ConvertToStartDate.StartDate("Today"), but that does not work. I get a red squiggly line under StartDate.
Thanks for your help,
Iris
from your code snippet up above, you would use:
=Code.ConvertToStartDate("Today")
I havent had the intellisense work on custom function code.
BobP
|||Works like a charm....Thanks!
Iris
sqlSunday, March 11, 2012
can't return zero when no rows exist using aggregate function sum
I'm having a heck of a time trying to get SQL Server 2000 to return a
zero (0) if no rows are returned in a sum() statement. I know in
Oracle you wrap an NVL around the whole shebang, and in Googling it
seems as if SQL Server should work this way, too. But I cannot get it
to work, I just keep getting null.
I have tried:
what I thought would work:
SELECT ISNULL(SUM(ISNULL(PointValue, 0)), 0)
FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
tbl_event_types et ON ae.[event type] = et.eventID
WHERE [File #] = '0001001047'
AND EventDate BETWEEN '2/24/2005' AND getdate()
GROUP BY [File #]
a case statement testing for null:
SELECT CASE
WHEN SUM(ISNULL(PointValue, 0)) IS NULL THEN 0
ELSE SUM(ISNULL(PointValue, 0))
END
FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
tbl_event_types et ON ae.[event type] = et.eventID
WHERE [File #] = '0001001047'
AND EventDate BETWEEN '2/24/2005' AND getdate()
GROUP BY [File #]
wrapping the whole select statement in ISNULL as a subquery:
SELECT ISNULL((SELECT SUM(ISNULL(PointValue, 0))
FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
tbl_event_types et ON ae.[event type] = et.eventID
WHERE [File #] = '0001001047'
AND EventDate BETWEEN '2/24/2005' AND getdate()), 0)
FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
tbl_event_types et ON ae.[event type] = et.eventID
WHERE [File #] = '0001001047'
AND EventDate BETWEEN '2/24/2005' AND getdate()
and then to make sure what I was getting back was null and not empty
...something:
declare
@.n_sum numeric(6, 2)
SELECT @.n_sum = ISNULL(SUM(ISNULL(PointValue, 0)), 0)
FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
tbl_event_types et ON ae.[event type] = et.eventID
WHERE [File #] = '0001001047'
AND EventDate BETWEEN '2/24/2005' AND getdate()
GROUP BY [File #]
print 'sum is: ' + convert(char(8), isnull(@.n_sum, 0))
sum is: 0.00
What the heck am I doing wrong? I tried setting ANSI_NULL off and on,
etc...but no go. I guess I could get around by using the variable and
then returning that to the VB (since this is a stored proc used to find
one value to return to the VB6 program), but that seems kind of messy.
I would appreciate any help!
TIA
PatCould you provide actual specs and desired results?
http://www.aspfaq.com/5006
> I'm having a heck of a time trying to get SQL Server 2000 to return a
> zero (0) if no rows are returned in a sum() statement.|||I need to say this - I inherited this code and database structure!!!!
CREATE TABLE [tbl_Attendance_Event] (
[EventCode] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[File #] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Event Type] [numeric](9, 0) NULL ,
[EventDescription] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[Excused] [bit] NULL ,
[EventDate] [smalldatetime] NULL ,
[EventDuration] [money] NULL ,
[PointValue] [money] NULL ,
[ConsecDayCount] [numeric](9, 0) NULL ,
[Consecutive_Days] [bit] NULL ,
[EventRemove] [bit] NULL ,
[EventRemoveDate] [datetime] NULL ,
CONSTRAINT [PK_tbl_Attendance_Event] PRIMARY KEY NONCLUSTERED
(
[EventCode]
) WITH FILLFACTOR = 90 ON [PRIMARY] ,
CONSTRAINT [FK_tbl_Attendance_Event_tbl_Event_Types
] FOREIGN KEY
(
[Event Type]
) REFERENCES [tbl_Event_Types] (
[EventID]
)
) ON [PRIMARY]
GO
CREATE TABLE [tbl_Event_Types] (
[EventID] [numeric](9, 0) IDENTITY (1, 1) NOT NULL ,
[EventDescription] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[EventPoints] [smallmoney] NULL ,
[ExcepID] [numeric](9, 0) NULL ,
[TardyLogic] [bit] NULL ,
[Minimum Minutes] [numeric](9, 0) NULL ,
[Maximum Minutes] [numeric](9, 0) NULL ,
[ExtendsYearWindow] [bit] NULL CONSTRAINT
[DF_tbl_Event_Types_ExtendsYearWindow] DEFAULT (0),
[RuinsPerfectMonthlyAttendace] [bit] NOT NULL CONSTRAINT
[DF_tbl_Event_Types_RuinsPerfectMonthlyA
ttendace] DEFAULT (0),
[LogEvent] [bit] NULL ,
[PayCodeEvent] [bit] NULL ,
[Paycode] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Consecutive_Days] [bit] NULL ,
[AddToDropOffPeriod] [bit] NULL ,
CONSTRAINT [PK_tbl_Event_Types] PRIMARY KEY CLUSTERED
(
[EventID]
) WITH FILLFACTOR = 90 ON [PRIMARY]
) ON [PRIMARY]
GO
There are currently no rows that match the query, but I want to get
back a zero if that is the case. In other words, no rows = 0 for my
purposes. This query is in a stored procedure that returns the number
of points an employee has, so if there are no points I'd like a zero,
to do further processing with that zero. I could mess with the VB code
to make it zero there if there's no rows in the recordset, but this is
something that I've done with Oracle and is very useful in lots of
cases. I've Googled and seen responses that the
isnull(sum(isnull(expression, value)), value) should work, so I'm
missing something here!
Thanks
Pat|||If you want to see the groups where no matching rows exist by the where
clause, then you have to use [ALL] in the group by clause.
-- this is to reproduce what is happening to you
select c1, isnull(sum(1), 0)
from (select 1) as t1(c1)
where (c1 = 2)
group by c1
-- this is what you want
select c1, isnull(sum(1), 0)
from (select 1) as t1(c1)
where (c1 = 2)
group by all c1
go
AMB
"miapjp@.gmail.com" wrote:
> Hi,
> I'm having a heck of a time trying to get SQL Server 2000 to return a
> zero (0) if no rows are returned in a sum() statement. I know in
> Oracle you wrap an NVL around the whole shebang, and in Googling it
> seems as if SQL Server should work this way, too. But I cannot get it
> to work, I just keep getting null.
> I have tried:
> what I thought would work:
>
> SELECT ISNULL(SUM(ISNULL(PointValue, 0)), 0)
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> GROUP BY [File #]
> a case statement testing for null:
> SELECT CASE
> WHEN SUM(ISNULL(PointValue, 0)) IS NULL THEN 0
> ELSE SUM(ISNULL(PointValue, 0))
> END
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> GROUP BY [File #]
>
> wrapping the whole select statement in ISNULL as a subquery:
> SELECT ISNULL((SELECT SUM(ISNULL(PointValue, 0))
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()), 0)
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> and then to make sure what I was getting back was null and not empty
> ....something:
> declare
> @.n_sum numeric(6, 2)
> SELECT @.n_sum = ISNULL(SUM(ISNULL(PointValue, 0)), 0)
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> GROUP BY [File #]
> print 'sum is: ' + convert(char(8), isnull(@.n_sum, 0))
> sum is: 0.00
> What the heck am I doing wrong? I tried setting ANSI_NULL off and on,
> etc...but no go. I guess I could get around by using the variable and
> then returning that to the VB (since this is a stored proc used to find
> one value to return to the VB6 program), but that seems kind of messy.
> I would appreciate any help!
> TIA
> Pat
>|||You are dealing with two separate questions.
1. What is the sum on each row when there are records
2. What are the number of records (only important if 0)
One possible solution:
SELECT into a temp table. If the temp table has no rows, insert a row with
0. SELECT back off the temp table for your return value.
Since you have a filter on [File #], another option is to select into a
value and then test @.@.RowCount and set the value to 0 if @.@.RowCount = 0.
SOmething like:
DECLARE @.ReturnValue decimal
SELECT @.ReturnValue = ISNULL(SUM(ISNULL(PointValue, 0)), 0)
FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
tbl_event_types et ON ae.[event type] = et.eventID
WHERE [File #] = '0001001047'
AND EventDate BETWEEN '2/24/2005' AND getdate()
GROUP BY [File #]
IF (@.@.ROWCOUNT = 0)
SET @.ReturnValue = 0
SELECT @.ReturnValue
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
***************************
Think Outside the Box!
***************************
"miapjp@.gmail.com" wrote:
> Hi,
> I'm having a heck of a time trying to get SQL Server 2000 to return a
> zero (0) if no rows are returned in a sum() statement. I know in
> Oracle you wrap an NVL around the whole shebang, and in Googling it
> seems as if SQL Server should work this way, too. But I cannot get it
> to work, I just keep getting null.
> I have tried:
> what I thought would work:
>
> SELECT ISNULL(SUM(ISNULL(PointValue, 0)), 0)
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> GROUP BY [File #]
> a case statement testing for null:
> SELECT CASE
> WHEN SUM(ISNULL(PointValue, 0)) IS NULL THEN 0
> ELSE SUM(ISNULL(PointValue, 0))
> END
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> GROUP BY [File #]
>
> wrapping the whole select statement in ISNULL as a subquery:
> SELECT ISNULL((SELECT SUM(ISNULL(PointValue, 0))
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()), 0)
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> and then to make sure what I was getting back was null and not empty
> ....something:
> declare
> @.n_sum numeric(6, 2)
> SELECT @.n_sum = ISNULL(SUM(ISNULL(PointValue, 0)), 0)
> FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
> tbl_event_types et ON ae.[event type] = et.eventID
> WHERE [File #] = '0001001047'
> AND EventDate BETWEEN '2/24/2005' AND getdate()
> GROUP BY [File #]
> print 'sum is: ' + convert(char(8), isnull(@.n_sum, 0))
> sum is: 0.00
> What the heck am I doing wrong? I tried setting ANSI_NULL off and on,
> etc...but no go. I guess I could get around by using the variable and
> then returning that to the VB (since this is a stored proc used to find
> one value to return to the VB6 program), but that seems kind of messy.
> I would appreciate any help!
> TIA
> Pat
>|||> There are currently no rows that match the query, but I want to get
> back a zero if that is the case.
Assuming that PointValue will always be positive if it *has* a value, you
can do this ugly stuff...
SELECT MAX(foo) FROM
(SELECT foo = COALESCE(SUM(PointValue),0)
FROM dbo.[tbl_Attendance_Event] ae INNER JOIN
tbl_event_types et ON ae.[event type] = et.eventID
WHERE [File #] = '0001001047'
AND EventDate BETWEEN '20050224' -- m/dd/yyyy is a terrible format
AND getdate()
UNION SELECT foo = 0) x|||>> ..get SQL Server 2000 to return a zero (0) if no rows are returned in a s
um() statement <<
SELECT COALESCE (SUM(i), 0) FROM EmptyTable;
However, what you are actually getting back is an empty set (ab nulo,
ex nulo) and the empty set is converted into a NULL. This is important
when you use EXISTS() predicates.|||>> There are currently no rows that match the query, but I want to get
back a zero if that is the case. In other words, no rows = 0 for my
purposes.
<<
then why don't you add a dummy row to every group:
select a, sum(b) from(
select a,b from some_table
union all
select distinct a, 0 from some_table) t|||Aha!
when I have the where clause limiting the sum, I don't need the group
by (right?). The original code also had the [file #] (again, not my
code, I don't make column names with spaces!!) in the select statement
even though it wasn't ever used - I don't know, I'm trying to make this
whole application work with bad code and bad underlying database
structure. In any case, I was trying to shoehorn in code to existing
code and not seeing the group by wasn't needed.
Thanks!!!!!
Sunday, February 12, 2012
Can't index functinon-based column
is a function. When I try to do so, I get the error:
'Line' table
- Unable to create index 'IX_Line_LineText'.
ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot
create index. Object 'fn_GenerateLineText' was created with the
following SET options off: 'ANSI_NULLS.'.
But when I created the function, the top part looks like this, so I am

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE FUNCTION dbo.fn_GenerateLineText
(
@.LaborLineId int
)
***
I have to index this column. How can I do it?
-KJYou'll need to ensure that
SET ANSI_NULLS ON
when you create the underlying table
Also I believe you need "with schemabinding" option for your function