SqlDecimal Function Parameters With NULL Values
Oct 4, 2007
Hi,
I have a CLR function that throws an error if one of the parameters is NULL. Am I using the IsNullable tag correctly or am I supposed to do this another way? The function simply formats decimal values using .NET culture information and returns a string. Thanks very much for any help. -- Erik
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic=true, DataAccess=DataAccessKind.None)]
[return: SqlFacet(MaxSize = 30, IsNullable=true)]
public static string FormatGeneralDecimal([SqlFacet(Precision = 28, Scale = 8, IsNullable = true)] SqlDecimal sqlDc,
[SqlFacet(MaxSize = 10)] string cultureName)
{
string result = null;
if (!sqlDc.IsNull)
{
CultureInfo ci = CultureInfo.CreateSpecificCulture(cultureName);
result = sqlDc.Value.ToString("G", ci);
}
return result;
}
It works great unless I call it with a NULL value for sqlDc, in which case I get this:
select [dbo].[FormatGeneralDecimal](NULL, 'de-DE')
Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "FormatGeneralDecimal":
System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
System.Data.SqlTypes.SqlNullValueException:
at System.Data.SqlTypes.SqlDecimal.ToDecimal()
at System.Data.SqlTypes.SqlDecimal.get_Value()
at MyFunctions.FormatGeneralDecimal(SqlDecimal sqlDc, String cultureName)
View 1 Replies
ADVERTISEMENT
Jun 23, 2015
I'm trying to do a Clr function wiht null values but I have an error. My Clr is like this:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;
using System.Text;
[code]...
A .NET Framework error occurred during execution of user-defined routine or aggregate "function":
System.InvalidCastException: La conversión especificada no es válida.
System.InvalidCastException:
en Microsoft.SqlServer.Server.ValueUtilsSmi.GetSqlInt16(SmiEventSink_Default sink, ITypedGettersV3 getters, Int32 ordinal, SmiMetaData metaData)
en UserDefinedFunctions.function()
View 5 Replies
View Related
Jun 15, 2015
I'm running the following test query on a single table:
SELECT sph.datestamp, sph.stocksymbol, sph.closing, DATENAME(dw, sph.datestamp),
CASE DATENAME(dw, sph.datestamp)
WHEN 'Monday' then 'Monday'
ELSE (SELECT CAST(sph2.datestamp AS nvarchar) FROM BI_Test.dbo.StockDB AS sph2 WHERE sph2.DateStamp = DATEADD(d, -1, sph.datestamp) AND sph2.StockSymbol = 'NYA')
END AS TestCase,
[Code] ....
And here's an example of the output I'm getting:
Why the exact same subquery in the THEN of the second CASE statement is returning NULL when the first one completes as expected?
View 7 Replies
View Related
Jun 29, 2015
I have tables and a function as representated by the code below. The names for objects here are just for representation and not the actual names of objects. Table RDTEST may have one or multiple values for RD for each PID. So the function GIVERD will return one or multiple values of RD for each value of PID passed to it.
When I run the following query, I get the required result except the rows for CID 500 for which PID is NULL in table T1. I want the rows for CID 500 as well with PID values as NULL.
SELECT A.CID,
A.ANI,
A.PID,
B.RD
FROM T1 AS A CROSS APPLY GIVERD(A.PID) B
CREATE TABLE [DBO].[RDTEST](
[PID] [INT] NULL,
[RD] [INT] NULL
)
[Code] ....
View 4 Replies
View Related
Jan 25, 2008
I have a pivot transform that pivots a batch type. After the pivot, each batch type has its own row with null values for the other batch types that were pivoted. I want to group two fields and max() the remaining batch types so that the multiple rows are displayed on one row. I tried using the aggregate transform, but since the batch type field is a string, the max() function fails in the package. Is there another transform or can I use the aggragate transform another way so that the max() will work on a string?
-- Ryan
View 7 Replies
View Related
Feb 23, 2007
I have a DTSX package which reads values from a fixed-length text file using a data reader and writes some of the column values from the file to an Oracle table. We have used this DTSX several times without incident but recently the process started inserting NULL values for some of the columns when there was a valid value in the source file. If we extract some of the rows from the source file into a smaller file (i.e 10 rows which incorrectly returned NULLs) and run them through the same package they write the correct values to the table, but running the complete file again results in the NULL values error. As well, if we rerun the same file multiple times the incidence of NULL values varies slightly and does not always seem to impact the same rows. I tried outputting data to a log file to see if I can determine what happens and no error messages are returned but it seems to be the case that the NULL values occur after pulling in the data via a Data Reader. Has anyone seen anything like this before or does anyone have a suggestion on how to try and get some additional debugging information around this error?
View 12 Replies
View Related
Jun 17, 2012
I am SSRS user, We have a .net UI from where we want to pass multi select values, but these values are comma separated in the database. how can I write a sql query such that when I select multi values on my UI, the comma separated values are take care of.
View 5 Replies
View Related
May 30, 2014
I am working with SP. How can we find out values of parameters when the SP is executed with the default values?
View 9 Replies
View Related
Dec 9, 2013
I have SQL Server 2012 SSIS. I have Excel source and OLE DB Destination.I have problem with importing CustomerSales column.CustomerSales values like 1000.00,2000.10,3000.30,NotAvailable.So I have decimal values and nvarchar mixed in on Excel column. This is requirement for solution.However SSIS reads only numeric values correctly and nvarchar values are set as Null. Why?
CREATE TABLE [dbo].[Import_CustomerSales](
[CustomerId] [nvarchar](50) NULL,
[CustomeName] [nvarchar](50) NULL,
[CustomerSales] [nvarchar](50) NULL
) ON [PRIMARY]
View 5 Replies
View Related
Mar 29, 2006
Hi
can somebody explain me how I can assign a NULL value to a datetime type field in the script transformation editor in a data flow task.
In the script hereunder, Row.Datum1_IsNull is true, but still Row.OutputDatum1 will be assigned a value '0001-01-01' which generates an error (not a valid datetime). All alternatives known to me (CDate("") or Convert.ToDateTime("") or Convert.ToDateTime(System.DBNull.Value)) were not successful.
Leaving out the ELSE clause generates following error: Error: Year, Month, and Day parameters describe an un-representable DateTime.
If Not Row.Datum1_IsNull Then
Row.OutputDatum1 = Row.Datum1
Else
Row.OutputDatum1 = CDate(System.Convert.DBNull)
End If
Any help welcome.
View 1 Replies
View Related
Mar 18, 2007
A have a multi-valued parameter (B) which is dependent on a single-valued parameter (A) on my report. When a value is selected in A, I want all matching values in B to be selected by default and the "Select All" option checked. To do this I have set the Default Values section in B to point to the same dataset as the "Available Values" section. Both A and B have default values so the report runs automatically.
One of the values in parameter A (say Value1) yields more values in parameter B than the other (say Value2).
If I run the report the first time with Value1 selected as the default for parameter A, all values in B are checked correctly. If I run the report with Value2 selected the first time and then change the selected value to Value2 and run my report, all values in B are displayed but only the values that were previously checked (when Value1 was selected), are now checked, leaving the "Select All" unchecked.
What am I doing wrong? Why are all the values in B not checked? The dataset is the same in "Available Values" section and "Default Values" section.
View 8 Replies
View Related
Nov 9, 2000
Hi,
My query "select blah, blah, rank from tablewithscores" will return results that can legitimately hold nulls in the rank column. I want to order on the rank column, but those nulls should appear at the bottom of the list
e.g.
Rank Blah Blah
1 - -
2 - -
3 - -
NULL - -
NULL - -
At present the NULLs are at the top of the list, but I do not want my ranking in descending order. Any suggestions?
Thanks
Dan
View 1 Replies
View Related
Jun 22, 2006
I have a UDF
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Text;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[SqlFunction(DataAccess = DataAccessKind.Read)]
public static SqlDecimal GetCustomPrice(SqlGuid Item_Key, SqlGuid Company_Key)
{
SqlDecimal retvalue = new SqlDecimal();
try
{
StringBuilder sqlstr = new StringBuilder();
sqlstr.Append("SELECT A.Price ");
sqlstr.Append("FROM Price A ");
sqlstr.Append("JOIN Link_Table B ");
sqlstr.Append("ON A.Price_Key = B.FKey ");
sqlstr.Append("JOIN Lookup C ");
sqlstr.Append("ON B.Lookup_Key = C.Lookup_Key ");
sqlstr.Append("AND C.Group_Name = 'Price_Type' ");
sqlstr.Append("AND C.Value = 'Custom' ");
sqlstr.Append("JOIN Item D ");
sqlstr.Append("ON B.PKey = D.Item_Key ");
sqlstr.Append("JOIN Link_Table E ");
sqlstr.Append("ON A.Price_Key = E.FKey ");
sqlstr.Append("JOIN Lookup F ");
sqlstr.Append("ON E.Lookup_Key = F.Lookup_Key ");
sqlstr.Append("AND F.Group_Name = 'Price_Type' ");
sqlstr.Append("AND F.Value = 'Custom' ");
sqlstr.Append("JOIN Company G ");
sqlstr.Append("ON E.PKey = G.Company_Key ");
sqlstr.Append("WHERE D.Item_Key = @Item_Key ");
sqlstr.Append("AND G.Company_Key = @Company_Key");
using (SqlConnection conn = new SqlConnection("context connection=true;"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlstr.ToString(), conn);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
SqlParameter para = new SqlParameter();
para.ParameterName = "@Item_Key";
para.SqlDbType = SqlDbType.UniqueIdentifier;
para.SqlValue = Item_Key;
cmd.Parameters.Add(para);
para = new SqlParameter();
para.ParameterName = "@Company_Key";
para.SqlDbType = SqlDbType.UniqueIdentifier;
para.SqlValue = Company_Key;
cmd.Parameters.Add(para);
DataSet ds = new DataSet();
adap.Fill(ds);
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
retvalue = SqlDecimal.ConvertToPrecScale(new SqlDecimal((decimal)ds.Tables[0].Rows[0]["Price"]),12,3);
}
}
}
}
catch (Exception e)
{
throw e;
}
return SqlDecimal.ConvertToPrecScale(retvalue, 12, 3);
}
};
The value in the record is a decimal 12,3 which is 0.950 and when it is returned from this UDF it is 1. Using the debuger the value is 0.950 until it gets to the calling program were it
is 1. I have looked for an answer all over the place with not much luck Can anyone help I will be in their debt.
Thanks
Larry
View 1 Replies
View Related
Feb 8, 2007
I am using SQL CLR Integration to create a series of stored procedures.
I am building and deploying from Visual Studio 2005 SP1 and everything is working well except for my stored procedures that have a SqlDecimal typed input argument. By default, the precision and scale of the SqlDecimal is deployed to SqlServer as (18,0).
How can I change this default?
This is an example of my stored procedure definition:
namespace Microsoft.Hurley.DataStore
{
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure(Name = DB.PROC.TEST.INSERT)]
public static Int32 insertTest(out SqlInt16 cTestID, SqlInt16 cOrgID, SqlString cName, SqlDecimal cPassPercentage, SqlByte cNumberQuestionsToDisplay, SqlByte cMaxNumberAttempts, SqlBoolean cIsActive)
{
...
return returnValue;
}
}
}
From SQL Server after the procedure is deployed:
[dbo].[insertTest]
@cTestID [smallint] OUTPUT,
@cOrgID [smallint],
@cName [nvarchar](4000),
@cPassPercentage [numeric](18, 0),
@cNumberQuestionsToDisplay [tinyint],
@cMaxNumberAttempts [tinyint],
@cIsActive [bit]
Thanks!
View 4 Replies
View Related
Sep 3, 2015
I have an SSIS package that imports data from an Excel file, replaces any value in Excel that reads "NULL" to "", then writes the data to a couple of databases.
What I have discovered today, is I have two columns of dates, an admit date and discharge date column, and what I need to do is anywhere I have a null value in the discharge date column, I have to replace it with the value in the admit date column.
I have searched around online and tried a few things using the Replace funtion in Derived columns but no dice so far.
View 3 Replies
View Related
Dec 4, 2007
Hello Everyone. I am a newbie to data mining. I hope that you can help.
I have run the same data mining query against the Decision Tree, Logistical Regession, Neural Network and Assocation Rules mining models. I created seperate tables to contain the results of each of these models. All of the tables have the same structure. The structure is a col#1 with a bigint datatype and col#2 with a numeric(5,5) datatype. All of the models have been successful with outputing the data to their respective tables except the Association Rules model. I am receiving the following error: " Failed to execute data mining query due to the following error: The given value of type SqlDecimal from the data source cannot be converted to type decimal of the specified target column." Is there something special that I need to do with my dmx statement to get the sqldecimal data to insert into the numeric column? What is different about the Association Rules model? I rechecked my dmx statement and it is the same for other models.
Let me know if you need more information.
Thanks
View 2 Replies
View Related
Apr 26, 2007
How do you configure a multi-value parameter so it will allow the user to not enter the parameter?
I'm using integer multi-value parameters. I can't set the parameter to allow null, and when I preview the report and leave the parameter blank, it tells me to enter at least one value. I tried it with string parameters, and the report just doesn't run in preview if you don't enter any values, even if you choose "allow blank".
How do you specify a multi-value parameter to allow "empty" or "null"?
View 5 Replies
View Related
Aug 23, 2007
I am using a SQLDataSource with Stored Procedures. The Select, Insert and Update all work well. However I cannot get the delete to work. My stored procedures are tested and verified and the parameter names are the same as the source columns. When I try to run the delete an error that the stored procedure expects the parameter @locationStationId, however this value passes properly for the Update command?!? I tried to change the parameter to original_locationStationID to pass the original value, however this result in Null being passed for the parameter.
I cannot understand why this works for Update and passes the location ID, but will not work for DELETE. Can anyone shed any light onto the matter?
Thanks.OldValuesParameterFormatString="original_{0}" UpdateCommand="spUpdateLocation" UpdateCommandType="StoredProcedure"
DeleteCommand="spDeleteLocation" DeleteCommandType="StoredProcedure">
<DeleteParameters>
<asp:Parameter Name="locationStationId" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="locationStationId" Type="String" />
<asp:Parameter Name="locationType" Type="String" />
<asp:Parameter Name="locationName" />
<asp:Parameter Name="division" Type="String" />
</InsertParameters>
View 3 Replies
View Related
Jun 27, 2006
I know it's unbelievable, but i didn't ever use SP before. Sorry for this noobish question, don't beat me for this - please ;-)
In my SELECT Query i like to have some (WHERE) paramteters le's say: ID, NAME and AGE. I allways programmicali generate a WHERE statement in relation to which parameters I really get, because not allwasy i get all the parameters together. This is fine for "normal" Tables.
How does this work with SP? If I don't get NAME, do I set the SP-Parameter NAME to null to unconsider it? Or do I have to make some IF statements in the SP to check, if NAME has some value?
Thanks for a short hint!
View 6 Replies
View Related
Mar 18, 2008
Hi,
I do have a stored procedure with parameters inside. I just want to ignore those parameters that are NULL so that my WHERE clause will not execute them anymore. Here's my code:
CREATE PROCEDURE SEARCHPATIENT
@patnCode varchar(10) = NULL,
@patnSurname varchar(20) = NULL,
@patnGivenName1 varchar(20) = NULL
AS
SELECT....
FROM ...
WHERE patnCode=@patncode AND
patnSurname =@patnSurname AND
patnGivenName1 =@patnGivenName1
BUT...
If the user passes @patnSurname as NULL, I got an SQL error message:
"There was an error executing the query.. Timeout expired... ". I was hoping I could write an WHERE clause where IT WILL ONLY EXECUTE those parameters WITH VALUE and IGNORE those NULLs.
Can someone help me on this?
Can I use IF THEN ELSE statement inside the WHERE clause?
Can I use CASE STATEMENT inside the WHERE clause?
Thanks in advance.
Joseph
View 3 Replies
View Related
Apr 25, 2007
I'm new to SQL Server, so if I'm doing anything stupid don't bemean :)I have a procedure that I use to return data based on optionalparameters. It works fine, except when the underlying data contains anull on one if the fields being searched.My system uses a default wildcard for all parameters, so this excludessuch records. I need a way to add in " OR fldName IS NULL " where theparameter is empty or '%'. I've looked at using CASE WHEN, but itdoesnt seem to like SQL Keywords being part of the WHEN clause.I'd hate to have to resort to executing concatonated strings made fromIF and ELSE statements. Just too messy and not at all pretty!Any Ideas? Here's what I've got:ALTER PROCEDURE [dbo].[procFindUnits]@strUnitIDnvarchar = '%',@strProjectNamenvarchar = '%',@strAddressnvarchar = '%',@strTenancynvarchar = '%',@strTenurenvarchar = '%'ASBEGINSET NOCOUNT ON;SELECTtblUnits.strUnitID,tblProjects.strProjectName,qryAddresses.Address_OneLine,lkpTenancyTypes.strTenancyType,lkpTenureTypes.strTenureTypeFROM tblUnits INNER JOINtblProjects ON tblUnits.intProjectID = tblProjects.intProjectIDLEFT OUTER JOINlkpTenancyTypes ON tblUnits.intTenancyType =lkpTenancyTypes.intTenancyType LEFT OUTER JOINlkpTenureTypes ON tblUnits.intTenureType =lkpTenureTypes.intTenureTypeID LEFT OUTER JOINqryAddresses ON tblUnits.strUnitID = qryAddresses.strUnitIDWHERE(tblUnits.strUnitID LIKE @strUnitID)AND (tblProjects.strProjectName LIKE @strProjectName)AND (qryAddresses.Address_OneLine LIKE @strAddress)AND (lkpTenancyTypes.strTenancyType LIKE @strTenancy)AND (lkpTenureTypes.strTenureType LIKE @strTenure)END
View 9 Replies
View Related
Dec 1, 2007
Report Parameters:
When I check "Allow null value" shouldn't <null> be in my dropdown list?
I am doing Microsoft Report in Visual Studio 2005 and all I am trying to do is allow null value combine with available values from a query.
View 10 Replies
View Related
Jan 19, 2008
i have a form where filter information is going to be keyed/selected.
the data from that form is copied into a struct regardless of whether each field has data in it or not (eg firstname may have been entered but not lastname,
so the struct would contain firstname = 'john' and lastname = null)
i then want to build an sql statement (not using stored procedures but just direct sql) from this struct data but obvioulsy can't just have
a statement that says 'select ID from theTable where firstname='john' AND lastname=''" as this won't bring back the right info, if anything at all.
i normally build the statements like this
Code Block
string sql = "select ID from MembersTemp where FirstName = '{0}'";
SqlCommand cmd = new SqlCommand(string.Format(sql, FirstName), _con);
_con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
List<int> result = new List<int>();
while (rdr.Read())
{
etc....
so really, what's the best way of building an sql statement where some search parameters won't hold a value and therefore need ignoring.
also, whilst i'm here, i use viz studio 2005 and sql server 2005 (express??), so that does mean i'm using TSQL as well??
View 10 Replies
View Related
Oct 29, 2007
I have created a report with a stored proc which takes a parameter whose default value is null. Now when I run my stored proc in Enterprise Manager without any params I get 4 rows otherwise with proper parameter I get 2 rows.
Now I set the params value to allow for Null and blank values. When I run the report if I provide parameter value it works fine but if i try to run it without any param it shows an empty report while the stored proc running without params shows 4 rows.
I have earlier sucessfully created reports where stored procs had 4 params out of which 3 where defaulted to null. And so I set the allow nulls, Allow Blanks values to be true for those params in Rep services. So when I selected value for 1st param and ran the report I got the desired report. But this time I have only one param which can be null. But its not working.
Thanks in advance.
View 1 Replies
View Related
May 30, 2006
I am using version 9.00.2047.00 SP1 of Visual Studio 2005.
Using ADO.NET, I have been unable to get the Execute SQL task to successfully return the value of an output parameter defined as varchar or nvarchar when the value is null. No other data types seem to have this problem, including the sql_variant data type.
Here is the stored procedure I am calling:
create proc spx
@in int = null output,
@vc nvarchar(10) = null output,
@dt datetime = null output
as
select
@in = null,
@vc = null,
@dt = null
return
The variables to which the three output parameters return their values have a data type of Object. The task runs fine when the integer or datetime parameters are used, and the variables can be identified as null using IsDBNull. But as soon as the nvarchar (or varchar) parameter is included, the task fails with this message:
"The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 1 ("@vc"): Data type 0xE7 has an invalid data length or metadata length."
I have seen a couple of postings that sound similar to this problem, but so far I have found no resolution. Any advice would be much appreciated.
Thanks,
Ron Rice
View 11 Replies
View Related
Apr 7, 2008
Hi
I am trying to view my reporting service web site for the first time,
but I've got this Error message "StringStartsWith can't accept null parameters"
I am using Widows Vista and
Report Manager and Report Server Web site has been set to Default web Site and
Windows Server Identity.BuiltIn Account has been set to Local System and
Web Service Identity.ReportServer and Report Manager has been set to Classic .Net App Pool.
Can anybody help me on this issue.
Best Regards
View 3 Replies
View Related
Apr 18, 2007
I have an event:
Private Sub SqlDataSourceIncome_Deleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSourceIncome.Deleted
Dim command As SqlClient.SqlCommand
command = e.Command
If command.Parameters("@nReturnCode").Value <> 0 Then
DROPDEAD()
End If
That fires from:
<DeleteParameters>
<asp:Parameter Name="nDeletebyId" Type="Int64" />
<asp:Parameter Name="nOtherId" Type="Int64" />
<asp:Parameter Direction="Output" Name="nReturnCode" Type="Int64" />
<asp:Parameter Direction="Output" Name="nReturnId" Type="Int64" />
</DeleteParameters>
End Sub
When I:
GridViewIncome.DeleteRow(GridViewIncome.SelectedRow.RowIndex)
But nReturnCode is ALWAYS NULL... I even did a stored procedure that just:
ALTER PROCEDURE [dbo].[sp_nDeletebyId]
@nReturnCode bigint output,
@nReturnId bigint output AS
SET @nReturnCode = 0
SET @nReturnId = 0
And STILL got nothing but the NULLS... the insert & update stuff works fine, with identical code... it's just the DELETED event that I can't seem to knock. Has anyone seen this before? The above sample stored proc did return 0 when executed one the server...
and, BTW, the row is deleted!
Chip Kigar
View 2 Replies
View Related
May 12, 2015
I'm trying to have a default or null value in the dropdown list of the parameters on SSRS report. The dataset is bound with the Dynamics-AX 2009 AOT query. In the screen shot below you can see that I need a show All option in the dropdown list.
View 7 Replies
View Related
May 10, 2005
Hi,
I basically do not want to return a null value as a result of using a sum function (using sum against 0 rows).
Is there a common way to avoid this?
Thanx
View 5 Replies
View Related
Mar 23, 2006
Can you use a padleft function on a null value of a field?
I get this when i try to padleft on a result from a db. This happens only when one of the fields are null.
Public member 'PadLeft' on type 'DBNull' not found.
View 4 Replies
View Related
Jul 22, 2007
Hi,I want to pass parameter in to LIKE functionIs there anyway to do thatThanks,Janaka
View 6 Replies
View Related
Jan 19, 2008
Hi, I wish to create a user defined funtion in sqlserver2005 with optional parameter list. So at the time of function calling the parameters should be a optional one. How can i do this? please help me .
View 2 Replies
View Related