I've built a sample CLR function with the following declaration....
CREATE FUNCTION GetManager(@DeptCode nvarchar(3)) RETURNS nvarchar(1000) WITH RETURNS NULL ON NULL INPUT AS EXTERNAL NAME Assembly1.[ClassLibrary1.MyVBClass].MyManager
It returns the value "Unknown" as it would have for any unknown DeptCode, as-programmed.
I'm of the theory it should have returned NULL without actually firing the function? Or is this only for non-CLR items... or stored procedures, not functions?
'check to see that student num is in the db Dim connect as SqlConnection Dim strSelect as String Dim cmdSelect as SqlCommand Dim strDbResult as SqlDataReader
connect = New SqlConnection(connStr) strSelect = "SELECT stu_num, stu_fname, stu_lname FROM " + stuTable + " WHERE stu_num=@stuNum" cmdSelect = New SqlCommand(strSelect,connect) cmdSelect.Parameters.Add("@stuNum", txtStdNum.text)
Dim stuFName as String Dim stuLName as String Dim stuEmail as String Dim strRandom as String Dim strPassword as String Dim i as Integer Dim charIndex as String Dim stuMailMessage as MailMessage Dim strHTMLBody as String
In my DB I have a table with the columns stu_num, stu_fname and stu_lname. Each of these columns contains rows with data. However, the proceeding code gives me this error: Invalid attempt to read when no data is present (line 58 --> stuFName = strDbResult("stu_fname") ).
What am I doing wrong here? How do I assign the stu_fname in the DB to the page level variable stuFName?
As a little aside how do I say "If no record was found matching stuNum Then" ... ??
I have a typical scenario here where I am trying to assign a variable a value using another variable, for that I am using two execute SQL task , the fisrt one assigns the first variable a value and then the second one uses the first variable to evaluate and then assigns a value to another variable. The first execute sql task works fine , however the second one fails with the following error
"failed with the following error: "An error occurred while extracting the result into a variable of type (DBTYPE_I4)". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. "
Here is the query I am using to assign the value in my second execute sql task
select (CASE
WHEN Sum(col1) <> 0 AND ? = 'M' THEN 'M'
WHEN Sum(col2) <> 0 AND ? >= 'T' THEN 'T'
WHEN Sum(col3) <> 0 AND ? >= 'R' THEN 'R'
ELSE 'S'
END) as Current
FROM dbo.TABLE1
I am passing the variable by mapping the parameters and then assigning the value using a single row result set. Can someone please tell me where am I going wrong?
Hi I'm new to SQL and I'm trying to build a store procedure. What I'm trying to find out is how to assign a variable a value from a table.
So, I declare a variable: DECLARE @variable int Then I want to assign a single int value to that variable that is already in a table. For instance the id value from a single row in a table.
I've tried SELECT INTO and SET, but nothing has worked so far and I'm lost after searching for a few hours.
I would like to assign the value of a variable to a column name of a table. For eg:
declare @sam varchar(100) set @sam = 'Insert' create table #temp(Sample varchar(100) not null) insert into #temp(Sample) Values(@sam) drop table #temp
I would like to generate a table whose column name should be generated dynamically. The value of @sam that is "Insert "should be set to the column name. Is there a way to assign like this. Can anyone please help me in achieving this.
1 20031012121212 200 (recordtype, CreationDateTime(YYYYMMDDHHMISS), Rec_Count) -- Header records 2 ABCD, XYZ, 9999, 999999999, 1234 ---- Detailed Record 2 ABCD, XYZ, 9999, 999999999, 1234 ---- Detailed Record
For the above given sample data I am having two outputs at Condition Split (based on the recordtype). I want to store the 1st record datetime value into a variable and then I want to use that variable value into 2nd and 3rd row.
Basically, detailed records would be stored into the database not the header record. Is there any way I can use the variable while doing processing for 2nd and 3rd records.
The problem I'm having is described below all this code.---------------------------------------------------------My content page has a SqlDataSource: <asp:SqlDataSource ID="sqlGetUserInfo" runat="server" ConnectionString="<%$ ConnectionStrings:RemoteNotes_DataConnectionString %>" SelectCommand="SELECT [UserFirstName], [UserLastName] FROM [Users] WHERE ([UserGUID] = @UserGUID)" onselecting="sqlGetUserInfo_Selecting"> <SelectParameters> <asp:Parameter Name="UserGUID" Type="String" /> </SelectParameters> </asp:SqlDataSource> -----------------------------------------------------Inside my OnSelecting event, I have: protected void sqlGetUserInfo_Selecting(object sender, SqlDataSourceSelectingEventArgs e) { sqlGetUserInfo.SelectParameters["UserGUID"].DefaultValue = Membership.GetUser().ProviderUserKey.ToString(); } ---------------------------------------------------------------------And, inside my Page_Load, the relevant code is: //String strUserFirstName = ((DataView)sqlGetUserInfo.Select(DataSourceSelectArguments.Empty)).Table.Rows[0]["UserFirstName"].ToString(); DataView dvUserDetails = (DataView)sqlGetUserInfo.Select(DataSourceSelectArguments.Empty); if ((dvUserDetails != null) && (dvUserDetails.Count > 0)) { DataRow drUserInfo = dvUserDetails.Table.Rows[0]; lblHelloMessage.Text = "Hello, " + drUserInfo["UserFirstName"].ToString() + ((drUserInfo["UserLastName"].ToString() == "") ? "" : " " + drUserInfo["UserLastName"].ToString()); } ---------------------Now, here's the problem. My "if" statement is never executing because "dvUserDetails" is null. However, when I break the execution and put awatch on the actual Select() statement, it shows a DataView with the correct return rows! You can see the commented line where I tried tobypass the DataView thing (just as a test), but I get an object reference is null error.The weird thing is that it was working fine one minute, then started getting "funky" (working, then not, then working, then not), and now it just doesn't work at all. All thiswithout me changing one bit of my code because I was checking out some UI flow and stopping and restarting the application. I've tracked downthe temporary files directory the localhost web server runs from, deleted all those files, and cleaned my solution. I've even triedrebooting, and nothing seems to make it work again.My relevant specs are VS2008 9.0.21022.8 RTM on Vista Enterprise x64.
Hello all, for a project I am trying to implement PayPal processing for orders public void CheckOut(Object s, EventArgs e) { String cartBusiness = "0413086@chester.ac.uk"; String cartProduct; int cartQuantity = 1; Decimal cartCost; int itemNumber = 1; SqlConnection objConn3; SqlCommand objCmd3; SqlDataReader objRdr3; objConn3 = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); objCmd3 = new SqlCommand("SELECT * FROM catalogue WHERE ID=" + Request.QueryString["id"], objConn3); objConn3.Open(); objRdr3 = objCmd3.ExecuteReader(); cartProduct = "Cheese"; cartCost = 1; objRdr3.Close(); objConn3.Close(); cartBusiness = Server.UrlEncode(cartBusiness); String strPayPal = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart&upload=1&business=" + cartBusiness; strPayPal += "&item_name_" + itemNumber + "=" + cartProduct; strPayPal += "&item_number_" + itemNumber + "=" + cartQuantity; strPayPal += "&amount_" + itemNumber + "=" + Decimal.Round(cartCost); Response.Redirect(strPayPal);
Here is my current code. I have manually selected cartProduct = "Cheese" and cartCost = 1, however I would like these variables to be site by data from the query. So I want cartProduct = Title and cartCost = Price from the SQL query. How do I do this?
Hello all, I'm creating a stored procedure in SQL Server 2000. I'm trying to count how many rows match a certain WHERE clause, and assigning this integer to a variable:
---------------- DECLARE @RowCount int,
SELECT COUNT(*) FROM Customers WHERE FirstName='Joe' ----------------
How can I assign the count that returns from the SELECT statement to the @RowCount?
I need some help regarding a conversion in a Script Task.
I am reading my variable values from a database with a sql task, the table has two columns, variable and variableValue. Looping through the recordset and setting the different variables works well, with two links: http://blogs.conchango.com/jamiethomson/archive/2005/02/09/SSIS_3A00_-Writing-to-a-variable-from-a-script-task.aspx http://sqlblog.com/blogs/andy_leonard/archive/2007/10/14/ssis-design-pattern-read-a-dataset-from-variable-in-a-script-task.aspx
setting the variable value only works well if the package variable is defined as string, because the db field is a varchar, trying to assign an integer for example brings up an error.
Therefor I tried something like CType: Dts.Variables("MyVar").Value = CType(MyRecordsetField,String), where the target datatype should be depending on the variable datatype instead of being assigned as a constant.
I have a smalldatetime field in a table that holds dates as 3/1/2008. If you run a select query on the field it will bring back the date as a datetime vairable. I reran the query using the following: select convert(varchar,cast((max(ENTRY_DTE))as datetime),101) This query brings me back the date as 03/01/2008.
When I utilize the same query and set the value to a declared variable, defined as datetime, it brings me back the date as : Mar 01 2008 12:00AM
I have tried several different ways to convert the date however as soon as appoint it to a declared variable I receive the same result!!
I've asked this question before and I've read the answers before and I still cannot get it to work. My task is simple, I want to use the execute sql task container to grab a value from a database and put it in a variable. I've done all the preliminary stuff such as running profiler to make sure that the package is getting the call to the database, setting up the ResultSet to be "single row" in the general tab, mapped the Result Set correctly, but nothing works. I get the same error every time.
This is my sql command:
select output_location as output_location from script_master
Result Set is set up like this:
Result Name: output_location ; Variable Name: User::output_location
Here is the error I get:
Error: 0xC002F309 at Execute SQL Task, Execute SQL Task: An error occurred while assigning a value to variable "output_location": "The type of the value being assigned to variable "User::output_location" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
".
I don't know what I'm doing wrong, I've followed all the instructions exactly on how to populate a variable in this container. My variable is set up as a string, if I change it to object I can get it to work. I think this is because the object is allowing nulls. I really believe that the variable is not populating and that is why I'm getting errors.
Please help. If you could provide step by step example's that would really make my day.
How to assign multiple values to emp1 variable separated by comma Ex: If ajay karthik vijay are employee names in emp table then emp1= ajay,karthik, vijay set emp1= (select employeename from emp) returns error error: subquery returns morethan one value
Okay, can I assign line x of a flat file to a variable, parse that line, do my data transformations, and then move on to line x+1?
Any thoughts?
In other words, I'm looking at using a for loop to cycle through a flat file. I have the for loop set up, and the counter's iterating correctly. How do I point at a particular line in a flat file?
Hi, I'm try to get the query second column value when it is assinged to a varchar variable. Ex:In SP below is statement I wrote SET @Values = (SELECT COL1,COL2 FROM TABLE) Question 1: How to access the COL2 value from @Value2? Question 2: How to access the other row values if above returns more than a row? Please send me the solution as soon as possible. Thanks-Vikash/Bala
In my SSIS package I am looping multiple flat file to load data into target table. I have used one variable to get that filename. I have error log table which used to log the invalid record which come from various files.
All are working fine , except I want to log the filename also in my error log table. How can we use the package variable to assign the variable value in script component.so that I can map the output column to target table. I have created Filename column in script component in output column tab.
The following works in query if I specify one student (PlanDetailUID) when running query. If I try to specify multiple students (PlanDetailUID) when running query, I get variable cannot take multiple entries. I assume I would need to replace (variables) in PART 2 with (case statements / using select everywhere) to get around the issue or is there a better way ?
I havethe following query which returns one row of data, however, the MedicalcodeID is NULL.
SELECT db1.dbo.Referral.ReferralGuidDigest, dbo.patient.PatientID, dbo.Consultation.ConsultationID, dbo.Staff.StaffID, db1.dbo.Referral.EffectiveDateTime AS EventDate, db1.dbo.Referral.Status AS ReferralStatus, db1.dbo.Referral.Mode AS ReferralMode, db1.dbo.Referral.ServiceType, db1.dbo.Referral.Urgency, db1.dbo.Referral.Direction, db1.dbo.Referral.Transport, db1.dbo.Referral.EndedDate, db1.dbo.Referral.ReceivedDate, dbo.lkupMedical.MedicalCodeID, db1.dbo.Referral.Term,
[code]...
It is clear from teh above - that the expected MedicalCodeID = 33959 and NOT NULL. I dont understand why SQL added the COLLATE SQL_Latin1_General_CP1_CS_AS to the query - am working on a database developed by another person. Could it be the ACode and ReadCode in dbo.lkupMedical is not set up with SQL_Latin1_General_CP1_CS_AS. How to implement to LkupMedical table....
I changed HIGHLIGHTED JOIN to Inner/Right but it never yielded any results, no record found..
I have a Data Flow Script Component(Destination Type) and in the properties I have a read/write variable called User::giRowCount
User::giRowCount is populated by a Row Count Component previously in the Data Flow.
After reading http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=97494&SiteID=1 it is very clear that you can actually only use variables in the PostExecute of a Data Flow Script Component or you will get an error "Microsoft.SqlServer.Dts.Pipeline.ReadWriteVariablesNotAvailableException: The collection of variables locked for read and write access is not available outside of PostExecute."
What I need to do is actually create a file in the PreExecute and write the number of records = User::giRowCount as second line as part of the header, I also need to parse a read/write variable such as gsFilename to save me hardcoding the path
-they must go in the PreExecute sub --workarounds please-here is the complete script component that creates a file with header, data and trailer --Is there any workaround
Public Class ScriptMain Inherits UserComponent 'Dim fs As FileStream Dim fileName As String = "F:FilePickUpMyfilename.csv" 'Dim fileName = (Me.Variables.gsFilename.ToString)
Dim myFile As FileInfo = New FileInfo(fileName) Dim sw As StreamWriter = myFile.CreateText Dim sbRecord As StringBuilder = New StringBuilder
Public Overrides Sub PreExecute()
sbRecord.Append("RECORD_START").Append(vbNewLine)
End Sub
Public Overrides Sub ParsedInput_ProcessInputRow(ByVal Row As ParsedInputBuffer)
Public Overrides Sub PostExecute() sbRecord.Append("RECORD_COUNT").Append((vbTab)) sbRecord.Append(Me.Variables.giRowCount.ToString).Append(vbNewLine) sbRecord.Append("RECORD_END").Append(vbNewLine) 'Now write to file before next record extract sw.Write(sbRecord.ToString) 'Clear contents of String Builder sbRecord.Remove(0, sbRecord.Length)
i have the following query to sum the total due balance for a customer:
select sum(outstanding)from out where customer = 'myvariable' the problem is when the customer has no outstanding it returns NULL is there a way to return 0 when there are no outstanding?
I am trying to script out the creation of database scripts. I am tryingto use @@servername in the statement. I found out the select@@servername returns NULL. I used sp_dropserver to drop any servernamesfirst, restarted SQL, ran sp_addserver 'servername' to add theservername, restarted SQL. select @@servername still returns NULL...Any ideas why this may be happening?Thanks,TGru*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
I am using the following C# code and T-SQL to get result object from aSQL Server database. When my application runs, the ExecuteScalarreturns "10/24/2006 2:00:00 PM" if inserting a duplicated record. Itreturns null for all other conditions. Does anyone know why? Doesanyone know how to get the output value? Thanks.------ C# -----aryParams = {'10/24/2006 2pm', '10/26/2006 3pm', 2821077, null};object oRtnObject = null;StoredProcCommandWrapper =myDb.GetStoredProcCommandWrapper(strStoredProcName ,aryParams);oRtnObject = myDb.ExecuteScalar(StoredProcCommandWrapper);------ T-SQL ---ALTER PROCEDURE [dbo].[procmyCalendarInsert]@pBegin datetime,@pEnd datetime,@pUserId int,@pOutput varchar(200) outputASBEGINSET NOCOUNT ON;select * from myCalendarwhere beginTime >= @pBegin and endTime <= @pEnd and userId = @pUserIdif @@rowcount <0beginprint 'Path 1'set @pOutput = 'Duplicated reservation'select @pOutput as 'Result'return -1endelsebeginprint 'Path 2'-- check if upperlimit (2) is reachedselect rtrim(cast(beginTime as varchar(30))) + ', ' +rtrim(cast(endTime as varchar(30))),count(rtrim(cast(beginTime as varchar(30))) + ', ' +rtrim(cast(endTime as varchar(30))))from myCalendargroup by rtrim(cast(beginTime as varchar(30))) + ', ' +rtrim(cast(endTime as varchar(30)))having count(rtrim(cast(beginTime as varchar(30))) + ', ' +rtrim(cast(endTime as varchar(30)))) =2and (rtrim(cast(beginTime as varchar(30))) + ', ' +rtrim(cast(endTime as varchar(30))) =rtrim(cast(@pBegin as varchar(20)))+ ', ' + rtrim(cast(@pEnd asvarchar(20))))-- If the @@rowcount is not equal to 0 then-- at the time between @pBegin and @pEnd the maximum count of 2 isreachedif @@rowcount <0beginprint 'Path 3'set @pOutput = '2 reservations are already taken for the hours'select @pOutput as 'Result'return -1endelsebeginprint 'Path 4'--safe to insertinsert dbo.myCalendar(beginTime, endTime,userId)values (@pBegin, @pEnd, @pUserId)if @@error = 0beginprint 'Path 4:1 @@error=' + cast(@@error as varchar(1))print 'Path 4:1 @@rowcount=' + cast(@@rowcount as varchar(1))set @pOutput = 'Reservation succeeded'select @pOutput as 'Result'return 0endelsebeginprint 'Path 4:2 @@rowcount=' + cast(@@rowcount as varchar(1))set @pOutput = 'Failed to make reservation'select @pOutput as 'Result'return -1endendendEND
I have the following code in my custom source component's AcquireConnection method -
if (ComponentMetaData.RuntimeConnectionCollection[0].ConnectionManager != null)
{
ConnectionManager cm = Microsoft.SqlServer.Dts.Runtime.DtsConvert.ToConnectionManager(ComponentMetaData.RuntimeConnectionCollection[0].ConnectionManager);
ConnectionManagerAdoNet cmado = cm.InnerObject as ConnectionManagerAdoNet;
if (cmado == null)
throw new Exception("The ConnectionManager " + cm.Name + " is not an ADO.NET connection.");
// Get the underlying connection object. this.oledbConnection = cmado.AcquireConnection(transaction) as OleDbConnection;
if (oledbConnection == null)
throw new Exception("The ConnectionManager is not an ADO.NET connection.");
isConnected = true;
}
The value of oledbConnection is null.
I am trying to invoke the above method within a package that I am trying to create dynamically. Any help ?
ConnectionManager cm = DtsConvert.ToConnectionManager(conMgr);
Microsoft.SqlServer.Dts.Runtime.Wrapper.ConnectionManagerAdoNet cmado = cm.InnerObject as Microsoft.SqlServer.Dts.Runtime.Wrapper.ConnectionManagerAdoNet;
OleDbConnection conn= cmado.AcquireConnection(null) as OleDbConnection;
}
}
In the sample above the conn is null.
To this query Darren replied to use the connection of type ADO.NET:System.Data.OleDb.OleDbConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 to create the connection.
Your call to GetConnectionsOfType("OLEDB"); will return native OLE-DB connections, not ADO.NET connections, using the OleDbConnection.
The connection type for the ADo>NET OLE-DB connection is -
but if user creates an New OLEDB Connection from the Connection Manager panel of the BIDS and selects the same from the custom UI how to get the underlying OLEDBConnection? the CreationName in this case is "OLEDB" and not ADO.NET:System.Data.OleDb.OleDbConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
I find it weird when decrypting a column from a baked up database and restoring it to another database. Here's the scenario:
Server1 has Database1. Database1 has Table1 with two columns encyrpted -- Card Number and SS Number Encryption and decryption in this Database1 is perfectly fine. Records are encrypted and can be decrypted too. Now, I tried to backup this Database1 and restore it to another server with SQL 2005 instance called Server2. Of course the columns Card and SS Numbers were encrypted. I tried decrypting the columns using the same command to decrypt in Database1, however, it returns a NULL value
Here's exactly what I did to create the encyprtion and decryption keys on the restored database: -- Create the master key encryption CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'myMasterPassword'
-- Create a symetric key CREATE SYMMETRIC KEY myKey WITH ALGORITHM = DES ENCRYPTION BY Password='myPassword'; Go
-- Create Card Certificate CREATE CERTIFICATE myCert WITH SUBJECT = 'My Certificate on this Server'; GO
-- Change symmetric key OPEN SYMMETRIC KEY myKey DECRYPTION BY PASSWORD = 'myPassword';
-- I then verified if the key is opened SELECT * FROM sys.openkeys
If I create a new database, say Database2 from that Server2, create table, master key, certificate, and symmetric key. Encrpytion and decryption on Database2 will work!
Any suggestions gurus? I tried all searches and help for almost 2 weeks regarding this issue but nobody could resolve this.
I have a SQL 2005 clustered server which is returning a Null value for @@servername. I find the server entry in sysservers. I have replication configured on this so i am not able to do a Sp_dropserver & sp_addserver as this acts as a publisher. The configured merge repication stopped working because of this issue and I am not able to delete replication as the the delete option uses @@servername which returns a null value. So I am struck in a loop.
Hi folks,I have an issue with a column I created in my query called Instance.SELECT Object_Id, Event_type, Audience, Subject, Provider, Academic_Year, Start_date, End_date, CONVERT(varchar, Academic_Year) + ' (' + CONVERT(varchar, Start_date, 103) + ') : ' + Event_type AS InstanceFROM EventsORDER BY Event_type Above is my query. The problem is because the start date column can be null, it also returns the Instance column as null for that row.I thought it would have just missed out the date and display the rest, but it doesn't.Is there any way I could get the Instance column to display a value, when the start date is null?ThanksEdit: Managed to sort it using ISNULL()
I have a built an application to manage the report-subscription on my ReportServer. I'm having some troubles with retrieving the subscription properties.
My problem: I can retrieve all my propertie except the schedule definition, when I deserialize it, the Sceduledefenition.Item always returns null.
I use the next code to deserialize it: ////////////////////////////////////////////////////////////////////////////////////////////////////// private XmlAttributeOverrides GetSchedule() { XmlAttributeOverrides xmlAttrOverride = new XmlAttributeOverrides(); XmlAttributes XmlAttr = new XmlAttributes(); XmlAttr.Xmlns = false; xmlAttrOverride.Add(typeof(ScheduleDefinition), XmlAttr); xmlAttrOverride.Add(typeof(MinuteRecurrence), XmlAttr); xmlAttrOverride.Add(typeof(DailyRecurrence), XmlAttr); xmlAttrOverride.Add(typeof(WeeklyRecurrence), XmlAttr); xmlAttrOverride.Add(typeof(MonthlyRecurrence), XmlAttr); xmlAttrOverride.Add(typeof(MonthlyDOWRecurrence), XmlAttr); xmlAttrOverride.Add(typeof(DaysOfWeekSelector), XmlAttr); xmlAttrOverride.Add(typeof(MonthsOfYearSelector), XmlAttr); return xmlAttrOverride; }
private ScheduleDefinition DeserializeScheduleDefenition(string MatchData) { XmlAttributeOverrides xmlAttrOverride = GetSchedule(); XmlSerializer ser = new XmlSerializer(typeof(ScheduleDefinition),xmlAttrOverride); Stream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(MatchData)); stream.Position = 0; return (ScheduleDefinition)ser.Deserialize(stream); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I'have tried almost everything, but could not find the solution.
Please, this is very important for me, so every tip or shared thought could be very helpfull.