HOW To Cast An AS ConnectionManager Into A SriptTask?

Dec 22, 2006

In fact, we could use AMO in the Sript Task, just by include the AMO.dll, many guys have talked about it on the forum.

But now, O my god, I met a big problem.

I declare a AS connectionManager in the SSIS package. In the Script Task I can't use it.

If this is a OEL DB ConnectionManager and connect to SQL Sever, I know I could write this inside the Sript Task:

Public myKPIConnection As SqlClient.SqlConnection

myKPIConnection = _
DirectCast(Dts.Connections("CYF.KPIOperation").AcquireConnection(Dts.Transaction), _
SqlClient.SqlConnection)

Then I could use myKPIConnection inside the Task.

But, How to do the similar thing to a AS ConnectionManager? I need to DirectCast the AS connectionManager to What?

By the way, the only thing I want to do is to Start an AS transaction inside the Sript Task, and let a Process Task outside to be enlisted in the trransaction. So I need to use the same AS connectionmanager.


Thanks.

View 2 Replies


ADVERTISEMENT

VSA And ConnectionManager - AcquireConnection

Jan 19, 2006

Hi all

In a SSIS Package I have defined a ConnectionManager to
a SQL Server 2005.
Now I am trying to query data in a Visual Studio for Application Script.

I tried the following:
Dim local_SQLConnectionManager As Microsoft.SqlServer.Dts.Runtime.ConnectionManager
Dim local_SQLConnection As New System.Data.SqlClient.SqlConnection
Dim local_SQLDataReader As System.Data.SqlClient.SqlDataReader
Dim local_SQLCommand As New System.Data.SqlClient.SqlCommand

local_SQLConnectionManager = Dts.Connections("Name of ConnectionManager")
local_SQLConnection = CType(local_SQLConnectionManager.AcquireConnection(null), System.Data.SqlClient.SqlConnection)
local_SQLConnection.Open()
local_SQLCommand.Connection = local_SQLConnection

local_SQLCommand.CommandText = "SELECT something"
local_SQLDataReader = local_SQLCommand.ExecuteReader()
If local_SQLDataReader.Read Then
Dts.Variables("Just a variable").Value = local_SQLDataReader.GetString(0)
End If
local_SQLDataReader.Close()

It always stops on the line with the AcquireConnection:
Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. and so on ....

Thanks for any help

Frank Uray

View 3 Replies View Related

Get FlatFile Columns Through ConnectionManager

Mar 29, 2006

The CreatePackage sample provided with SQL Server programmatically creates a package that has a source type of OLEDB to a flat file destination. I am building exactly the opposite, source=flatfile, destination=SQL Server. I expect that will be a more common scenario is using SSIS.

The problem I have is populating the source columns in the FlatFileSource connection manager programmatically. I know it can be done because it happens when you build a package in Visual Studio. What I'd like to know is how to do it programmatically in the object model. How can I interrogate the datasource through the connection manager to find out what columns it has? If I know, I can add the columns to the connection manager. My sample below does this, but it doesn't know the number of columns in the source so that value is hardcoded. I'm guessing there is a better way to do this than what I've got below.

How can I find the number of columns in my source so I can add the columns to the connection manager?

Thanks.



Private Sub AddColumnsToFlatFileConnectionManager()
Dim ff As wrap.IDTSConnectionManagerFlatFile90 = Nothing

For Each cm As ConnectionManager In _Package.Connections
If cm.Name.Equals(_ExternalConnectionID) Then
ff = TryCast(cm.InnerObject, wrap.IDTSConnectionManagerFlatFile90)
DtsConvert.ToConnectionManager90(cm)
End If
Next

If Not ff Is Nothing Then

Dim col As wrap.IDTSConnectionManagerFlatFileColumn90
Dim name As wrap.IDTSName90
Dim Min As Int32 = 0
Dim Max As Int32 = Min + 3 ' *** HARDCODED LIMIT ***

For cols As Integer = Min To Max
col = ff.Columns.Add()

If cols = Max Then
col.ColumnDelimiter = vbCrLf
Else
col.ColumnDelimiter = ","
End If

Dim width As Int32 = 50
Dim DataType As wrap.DataType = wrap.DataType.DT_STR

col.ColumnType = "Delimited"
col.DataType = DataType
col.MaximumWidth = width
col.DataPrecision = 0
col.DataScale = 0
col.ColumnWidth = width
name = TryCast(col, wrap.IDTSName90)
name.Name = "Column " & cols.ToString

Next

End If

End Sub

View 4 Replies View Related

Password Property In ConnectionManager

Jan 18, 2007

I'm developing a custom manager in SSIS that has several properties defined. One property is a password string that is visible in clear text in the properties pane. I'm trying to figure out how to create a masked field in the properties pane that will mask the text and not present this in clear text. Can someone send me instructions or code samples in C# for doing this? BOL doesn't provide any information on doing this.

View 3 Replies View Related

Save ConnectionManager For Future Use

Dec 12, 2007

Hello,

I just create FLATFILE connection manager from UI, and now I would like save this connection manager for future use. I am not able to do this and now I am really stuck in the middle of coding.



ConnectionManager class has SaveToXML and LoadFromXML methods from IDTSPersist, these methods are not for use, but I am able to save CM to XML, however not load. Every try for loading ends with error 0xC0011008. The XmlNode.Name == "DTS:ConnectionManager"



CM class is not serializable, thus standard .NET feature is not working, also is sealed.



IDTSConnectionManagerFlatFile90 of cm.InnerObject is not serializable either, because it is interface and cm.InnerObject cannot be cast to ConnectionManagerFlatFileClass because is the COM.



Is there any way, how to save and load ConnectionManager besides writing of tons of code for each of connection manager type?


I am able to save and load package with connection manager, but it is not exactly what I want. Also is there possibility to work with XML in packages, but this is not "right".

Thanks

Erik

View 7 Replies View Related

SSIS ConnectionManager In Script Task

Apr 8, 2008

I have a SourceConnectionExcel in my SSIS package.  This path to this is configured in the .dtsConfig file.  My question is, how can I get the path from within a Script Task? 
 I ws thinking something like this might work, but no dice.
Dts.Connections("SourceConnectionExcel").Properties("ExcelFilePath")

View 4 Replies View Related

Child Package ConnectionManager Visibility

Jul 20, 2006

Hopefully a simple question about parent-child package relationship. For this example, let's say I have a simple setup - one parent package: parent.dtsx, and one child package: child.dtsx. The parent package calls the child package via the ExecutePackage Task.

If I add an OleDB ConnectionManager to the parent package called MySqlConnectionManager, should I be able to reference this connection via a script task (or custom component) from my child package? I realize that I will have a problem doing this at design time, but I thought I could get around it with the script task or custom component. That said, when I look in the Connections collection at run-time from within my child package, I do not see the parent package's MySqlConnectionManager. Am I missing something, or is this the way it was intended to work?

Thanks,

David

View 6 Replies View Related

Accessing ConnectionString From ConnectionManager In A Script Task Ends With Login Failed! WHY!!

Feb 8, 2007

So in a script task for one of my packages I have a connection manager to an dtsConfig OLE DB.

This is the code

Dim ConnectionString As String = Dts.Connections("db_stage").ConnectionString
Dim sqlConnection As SqlConnection = New SqlConnection(ConnectionString )

I get a login failed for
user...But if I hardcode the connectionString, including the password this works.

1) Why is it that the ConnectionString from the connection manager omits this password?
2) Since this is an OLE DB, is there anyway to set the Data Source Designer to omit the "Provider=ABCDED.1" section?

Thanks!
Tony

View 5 Replies View Related

CAST

Jan 16, 2007

Hi
Can anyone tell me how I can CAST these fields AS DECIMAL (19, 2) please?

(SELECT ([Total students] - [withdrawn] - [transferred] - [cancelled]) / [total Students] * 100 AS [Percentage Retained])

Thanks
Daniel

View 6 Replies View Related

CAST

Dec 14, 2007

I have

CASE
WHEN (a.type_id in (9))
THEN a.duration
ELSE 0 --CAST ( expression AS data_type )
END 'Time'


I need the duration to be displayed if type is 9 only.
so otherwise id ideally want 'N/A' displayed..
but it won't display it as its not an int ..

is there a way i can just display it temporarily
instaed of 0 ?

View 5 Replies View Related

Need Help With A CAST

Feb 5, 2008

I am having a little trouble with the CAST in my SELECT statement below. Any help is greatly appreciated.



SELECT
group_id_ AS [Group ID],
vendor_id_ AS [Vendor ID] ,
project_id_ [Project ID],
resource_id_ [Resource ID],
vendor_price_ [Old Price],
new_price_ [New Price],
(CAST (new_price_/vendor_price_)-1 AS DECIMAL (4, 2)) AS [Difference]
FROM hbs_vnpq
WHERE (group_id_ = '210') AND (vendor_id_ = '08416') AND (new_price_ >0) AND (vendor_price_ >0)
ORDER BY [Difference]





Server: Msg 1035, Level 15, State 10, Line 7
Incorrect syntax near 'CAST', expected 'AS'.

View 5 Replies View Related

Specified Cast Is Not Valid

Sep 11, 2006

im doing a sum on a table and it either returns a number in decimal format or 'null' .  The problem is when it returns null i want it to just make the text say '0.00'.  So i did a test on the object that if it returns NULL just print  '0.00' but if it is not null it tells me that there is a number there and i want to store that as a decimal and print it out.  But i get an error for a type cast when im not it should not even be going to that part of the code. In the code below the first executescaler will return null so it should just go straight to the else.  But it gives me the type cast error in the if that shouldnt be seen.  The error and code are below. //Borrower NSF FEES
cmd.CommandText = "select sum(itemamount) from postmtdtls where loanid='" + LoanID + "' and Transactioncode = '310'";
object temp = cmd.ExecuteScalar();
if (temp != null)
{
decimal B_NSFFees = ((decimal)cmd.ExecuteScalar());
borrowerPayoff_NSFFees.Text = String.Format("{0:#,#.##}", B_NSFFees).ToString(); //Borrower NSF FEES
}
else
{
borrowerPayoff_NSFFees.Text = "0.00"; //borrowerPayoff_NSFFees.Text = "0.00";
}  Server Error in '/WebSite5' Application. Specified cast is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Specified cast is not valid.Source Error: Line 774: if (temp != null)
Line 775: {
Line 776: decimal B_NSFFees = ((decimal)cmd.ExecuteScalar());
Line 777: borrowerPayoff_NSFFees.Text = String.Format("{0:#,#.##}", B_NSFFees).ToString(); //Borrower NSF FEES
Line 778: }Source File: c:ProgrammingFilesWebSite5InvestorPool.aspx.cs    Line: 776 Stack Trace: [InvalidCastException: Specified cast is not valid.]
InvestorPool.GetLoanInfo(String LoanID) in c:ProgrammingFilesWebSite5InvestorPool.aspx.cs:776
InvestorPool.MortAccountText(Object sender, EventArgs e) in c:ProgrammingFilesWebSite5InvestorPool.aspx.cs:660
System.Web.UI.WebControls.TextBox.OnTextChanged(EventArgs e) +75
System.Web.UI.WebControls.TextBox.RaisePostDataChangedEvent() +124
System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +7
System.Web.UI.Page.RaiseChangedEvents() +138
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4507
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42

View 10 Replies View Related

Using CAST From Varchar To Int

Oct 15, 2006

I am pretty new to SQL for SQL Server 2005. In a view I have a column CAST(Field1 as int). Field1 is a varchar.All works well except when the data is not numeric such as a '?' or '*'.How can I get around this, with a case statement, coalese?I only want to perform the CAST on valid numeric values.The valid values in the varchar field are blank, null,'0','1','2','3','4','5','?','*' and maybe othersThanks

View 11 Replies View Related

Cast Problem

Aug 31, 2007

If I run the following query in SQL Server Management Studio it returns the correct results: (Searching the table for the field "SpecimenID (an INT)" against the data entered (a Text Field - "7575-01")  from the submitted form.
SELECT     ClinicalID, SpecimenID, PatientID, LabID, Accession, Bacillus, Francisella, Yersinia, Brucella, Burkholderia, Coxiella, Staphylococcus, Other,                       OtherExplanation, CollectionDate, strddlTransportMedium, strddlSpecimenSource, UserName, Test, SpecimenCount, DateAndTimeFROM         ClinicalSpecimenWHERE     (SpecimenID = CAST('7575-01' AS VARCHAR(50)))ORDER BY SpecimenID DESCHowever, when I try to use the same logic in the ASPX.VB code behind page, as follows below, I either get an error message (Syntax error converting the varchar value '' to a column of data type int.) or record not found.... Can someone please explain what I am missing here....
MySQL = "SELECT * FROM ClinicalSpecimen WHERE SpecimenID = CAST(('" & AccessionPresent & "') AS VARCHAR(50))"
*"AccessionPresent" is the value of the text field retrieved from the form.
I guess what I am really asking is how can I search for an INT value in a table using a VARCHAR Field.
Thank you for any or all assistance !!!

View 6 Replies View Related

Cast Or Convert

Feb 18, 2008

 Hi,I want to turn int to double/decimal  in microsoft sqlSHould i use cast or convert?if so, how i do it thanks, 

View 1 Replies View Related

If / IIf - Cast Exception

May 29, 2008

Hi over there,I hope this question is not too simple, but I didn't manage to figure out why...I would need an explanation for following issue:I'm reading data from a database (MSSQL) and it the column "PersonBirthday" is DBNull.I wanted to prevent the error (Textbox.Text = DBNull) with an IIF. The thing is I get thistypecast exception:"Conversion from type 'DBNull' to type 'Date' is not valid." This code is NOT working, why?    txtPersonBirthday.Text = IIf(IsDBNull(.Item("PersonBirthday")) =
True, String.Empty,
CDate(.Item("PersonBirthday")).ToString("yyyy-MM-dd")) When I'm using this code, which is for me obviously the same, just with an if-block it works,and I want to know why - please explain.           If IsDBNull(.Item("PersonBirthday")) Then                txtPersonBirthday.Text = String.Empty            Else                txtPersonBirthday.Text = CDate(.Item("PersonBirthday")).ToString("yyyy-MM-dd")            End IfThanks in advance,cheers,uquandux                    If IsDBNull(.Item("PersonBirthday")) Then                txtPersonBirthday.Text = String.Empty            Else                txtPersonBirthday.Text = CDate(.Item("PersonBirthday")).ToString("yyyy-MM-dd")            End If 

View 3 Replies View Related

Varbinary Cast

Sep 16, 2004

Can anyone tell me what varbinary casts to ?? can I do this int[] temp=(int)DataReader["varbinaryColumn"]. Or is byte[] temp the appropiate protocol.

View 1 Replies View Related

Specified Cast Is Not Valid

Apr 7, 2006

Can't seem to find why I'm getting this error: Specified cast is not valid.
Ok, using a stored procedure for SQL Server 2000 and here is the main part of it:
 SELECT id, rank, firstName, lastName, service, status, createdTime FROM   accessRequest WHERE  lastName LIKE @tLastName     AND    firstName LIKE @tFirstName
And the C# code behind from the class file:
SqlDataReader spResults;
conn.Open();
spResults = command.ExecuteReader();
while( spResults.Read() )
{
AccessRequestSearch request = new AccessRequestSearch( (int)spResults.GetInt32( 0 ), spResults.GetString( 2 ), spResults.GetString( 3 ), spResults.GetString( 1 ), spResults.GetString( 4 ), spResults.GetString( 5 ), Convert.ToDateTime(spResults.GetString( 6 )));
searchResults.Add( request ); // Add to Array List
}
spResults.Close();
The part in red is where I think it's happening because that is what I just added to the request.  createdTime in the table is set as DateTime.
Can anyone see what I am missing here?
More info is available if needed.
Thanks,
Zath

View 1 Replies View Related

Help With Conver/Cast

Oct 26, 2002

I have a table with a column called Sample_Date_and_Teime with a row definition of char(16). What is stored in this table is a date (ie. 1020621141517000) The first char is the century, the next are the year, the next two are the month, the next two are the day, the next 2 the hour, the next two are the minutes, and the next 2 are the seconds and the last 3 are to be ignored... what I need to do is write a select statement that converts this column into a datetime so that I can then do a insert into a new table by selecting from this table based on a date range. PLEASE HELP:confused: :confused: :confused:

View 1 Replies View Related

CAST/Convert

Mar 15, 2006

I need Query syntax to cast/convert values as follws.

Val.: 00005000010260002180 - Result must be: 5.1.2600.2180
Val.: 00005000000213400001 - Reslut must be : 5.0.2134.1

Dots must also be contained in result

View 2 Replies View Related

Check If Cast Is Possible

Feb 10, 2005

I use to import data from DBF Clipper databases into SQL Server. When a table is just imported its date fields have string format. I need to copy their data to tables of database where they ahve to be converted into date. Direct operator INSERT doesn't convert properly (I've not successed in changing default date format so it'll be covertable) but using CAST I can get result of strings like 13.05.1970 0:00:00 as datetime type. But not all records can be coverted this way. For ones can't be converted I've solved to make NULL fields there. But I don't know how to make CAST operation return NULL when convertion isn't possible. The query
INSERT INTO people_temp
(reg_num, surname, stname, patronymic, foreing, gender, birthdate, fam_pos, dwell_type, children, nation, par_not, region, stud_fml, parn_fml,
com_prob, sp_prob, sn_passport, nn_passport, dv_passport, wg_passport)
SELECT STUDENTs_temp.REG_NOM, STUDENTs_temp.FAMILY, STUDENTs_temp.NAME, STUDENTs_temp.PARN_NAME, STUDENTs_temp.INOSTR,

STUDENTs_temp.SEX,
CAST(PSPR_temp.DATA_BORN AS smalldatetime), PSPR_temp.SEM_POL, PSPR_temp.XAR_JT, PSPR_temp.CHILDREN,

PSPR_temp.NATION,
PSPR_temp.SV_ROD1 + PSPR_temp.SV_ROD2 AS Expr1, PSPR_temp.REGION, PSPR_temp.STUD_FML,

PSPR_temp.PARN_FML,
PSPR_temp.OB_STAJ, PSPR_temp.SP_STAJ, PSPR_temp.SN_PASPORT, PSPR_temp.NN_PASPORT, PSPR_temp.DV_PASPORT,
PSPR_temp.WG_PASPORT
FROM STUDENTs_temp INNER JOIN
PSPR_temp ON STUDENTs_temp.REG_NOM = PSPR_temp.REG_NOM
gets an error 'The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value'. Tell me please how can make type casting return NULL if convertion isn't possible.

View 2 Replies View Related

CAST Statement

Feb 28, 2006

It must be something I'm overlooking but I keep getting an error message that this statement can't parse.

UPDATE product SET supplier = LEFT(supplier,LEN(supplier-4)) + CAST( '2100' AS varchar(4)) WHERE actualid = 'IS2100-CO2-CO2-0-4-I'

Any help would be greatly appreciated.

View 2 Replies View Related

CAST Or Convert

Oct 8, 2014

Have the following in my SELECT statement, which I'm having issues with when I modify it to include a CAST or a CONVERT.

CONCAT(PER.[PERSON-REF],ROW_NUMBER() OVER (PARTITION BY PER.[PERSON-REF] ORDER BY TEN.[tenancy-ref])) AS 'ID'How do I convert or cast it to a varchar (20)?

View 8 Replies View Related

How To Run CAST On Duration

May 13, 2015

I found this nifty code on stackoverflow that works well but I'm trying to send the results to a text file and the column lengths are huge. I used CAST for the first line and it worked great but I can't seem to make it work with duration. Here's the original code:

SELECT
j.name,
h.run_status,
durationHHMMSS = STUFF(STUFF(REPLACE(STR(h.run_duration,7,0),
' ','0'),4,0,':'),7,0,':'),

[code]....

how to run a CAST on DURATION?

View 5 Replies View Related

Cast Formula

Apr 10, 2008

I have a quick question. created a report with this formula below. It works when I put a date range from 1-1-2007 to 2-1-2007, but when I put in a date range of 03-01-2008 through 03-31-2008. i get an error message of arithmetic overflow error converting numeric to data type numberic.

So instead of haveing the formula below be (4,2) I put it as (5,2) and now it work. Why is that?

CAST(clm_sppo / clm_tchg * 100 AS decimal(4, 2)) AS PercentSavings

View 3 Replies View Related

Cast DATETIME

Apr 24, 2008

Hi all,

i need help for deleting the time from a datetime type

what i mean is that instead of
2007-08-15 01:30:00.000
i would get
2007-08-15 00:00:00.000

many thanks

View 2 Replies View Related

Cast String To Int

Apr 27, 2008

Hi ,

I have a problem with casting a string number to int.
for exmaple i have the number '0110' (string) and i would like it to be 110. or '0001' to be 1.
i tried to do:
cast(MyNUM as int) .
but i get "Syntax error converting the nvarchar value 'O322' to a column of data type int."

is anyone have any idea how to solve it ?

thanks

View 3 Replies View Related

Help In Cast Function!

Mar 8, 2006

Hi,

I have a table with the following structure:
Table: Meeting
ID integer not null
Desc text null

Here Col 'Desc' is a text type stores description. I have used the following UPDATE query:
UPDATE Meeting SET Desc='New Updated text......' + ' ' + CAST(Desc as varchar) WHERE ID=100

Issues:
1. Since i did'nt specify lenth for varchar it takes only 30 chars from existing value and added to the edited text.
2. If i give like this CAST(Desc as varchar(8000)); it might take only first 8000 chars; remaining would be truncated correct? I assume that will happen.
3. If i don't use CAST i get error msg: "Invalid operator for type.."
Is there any work around in this situation? or better way to do it.

Looking for your help.
Thanks
BoB

View 2 Replies View Related

DATE Cast

Oct 19, 2006

Hello Everyone,

How do I change the format of the Date:

2006-06-01 00:00:00.000

to this:

06-01-2006.

I believe this can be done with a Cast.

Am I correct?

TIA


Kurt

View 6 Replies View Related

Error When Using Cast

Dec 10, 2007

Hi, I'm very new to SQL. Trying to sum two fields, but I have to change the datatype first. Here's the code and the error message I receive. Any help would be appreciated.

SELECT TS_RESPONSIBLE, TS_STATUS, TS_USER_07, SUM(TS_USER_07 * TS_STATUS) AS value
FROM TEST_54_VW
GROUP BY TS_RESPONSIBLE, TS_STATUS, TS_USER_07
WHERE CAST(TS_USER_07 AS INTEGER)

Incorrect syntax near the keyword 'WHERE'.

View 13 Replies View Related

CAST Problem

Jan 10, 2008

I have a problem with CASTING

I have a CASE stmt, i check a var that is an int in the db, but based on values i wanna display strings.

so

CASE var1
WHEN var1 = 51 THEN 'Level 1'
WHEN var1 = 52 THEN 'Level 2'
ELSE var1
END as x


This gives me Conversion failed when converting the varchar value 'Level 1' to data type int.

Fair enough
but when i try to cast it it still gives me the same error ?

CASE CAST(var1 as varchar(10))
WHEN var1 = 51 THEN 'Level 1'
WHEN var1 = 52 THEN 'Level 2'
ELSE var1
END as x

View 2 Replies View Related

CAST Command

Oct 22, 2005

I am using MS-Access as a front end for my MS-SQL DB. I have a sql view thatuses the following:SELECT TOP 100 PERCENT RECID, PATNUMBER AS [PAT #], SVCCODE AS [ServiceCode], QTY, PROF_CHRGS AS [Pro Fee's'], AMOUNT,BILLDATE AS [Bill Date], CHKAMT AS [Check Amt], PSDATEAS [Service Date], POSTDATE AS [Post Date], TRNSCODE AS [T Code],TRLR AS [T Code Desc], SUBSTRING(CAST(SVCCODE ASvarchar), 1, 4) AS [Dept #]FROM dbo.PAT_TransactionsORDER BY PATNUMBER, SVCCODEMy problem is the cast command. Will this sql view works and cast theSVCCODE field into a varchar, I need to cast the reseult of this,SUBSTRING(CAST(SVCCODE AS varchar), 1, 4) AS [Dept #], back in to a decimalformat. I am dropping this view onto a form and need to link to a field onthe form that is in decimal format.The only way I could get this to work was to create another view, based onthe one above, and cast the [Dept #] field back into the decimal format. Isthere any better way to do this? Can I nest the Cast command?Hope this makes sense.Thanks in advance.Mikem charney at dunlap hospital dot org

View 3 Replies View Related

Cast Problems With CLR

Sep 29, 2006

hi,

i have looked at several guides, and have come up with some code, although for some reason i am unable to get it to work, and receive an error:

Msg 6260, Level 16, State 1, Line 1
An error occurred while getting new row from user defined Table Valued Function :
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Object[]'.
System.InvalidCastException:
at UserDefinedFunctions.FillRow(Object obj, String& PID)
.


Below is my code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

using System.Collections;

public partial class UserDefinedFunctions
{
const string SELECT =
@"SELECT pointData.PID
FROM pointData
INNER JOIN pointDevices ON pointData.PID = pointDevices.PID
WHERE pointDevices.UUID = @UUID AND
DATEADDED >= @DATE_START AND
DATEADDED <= @DATE_STOP
ORDER BY DATEADDED";

[SqlFunction(FillRowMethodName = "FillRow", DataAccess = DataAccessKind.Read, TableDefinition="PID nvarchar(50)")]
public static IEnumerable createJourney(SqlString UUID, DateTime DATE_START,DateTime DATE_STOP, SqlDouble JOURNEY_DELAY, SqlDouble JOURNEY_DISTANCE)
{
ArrayList RAW_PID_LIST = new ArrayList();

using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();

SqlCommand command = new SqlCommand(SELECT,conn);

command.Parameters.AddWithValue("@UUID",UUID);
command.Parameters.AddWithValue("@DATE_START",DATE_START);
command.Parameters.AddWithValue("@DATE_STOP",DATE_STOP);

SqlDataReader reader = command.ExecuteReader();

using (reader)
{
while (reader.Read())
{
RAW_PID_LIST.Add(reader[0]);
}
}
}

return RAW_PID_LIST;
}

private static void FillRow(Object obj, out string PID)
{
object[] row = (object[])obj;

PID = (string)row[0];
}
};


could someone give me a clue as to why i might be getting this error please.

thank you.

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved