How To Get Query Second Column Value/other Rows While Assigning To A Variable In A Stored Procedure?
Feb 6, 2008
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
View 3 Replies
ADVERTISEMENT
Aug 13, 2007
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
View 4 Replies
View Related
Mar 25, 2008
Hi,
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.
Thanks,
Sana.
View 1 Replies
View Related
Nov 27, 2014
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 ?
CREATE TABLE #AWP (
[TransDate] [datetime] NULL,
[Description] [varchar](1000) NULL,
[Amount] [float] NULL,
[TotalDueNow] [float] NULL,
[code]....
View 4 Replies
View Related
Apr 27, 2006
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?
Thanks
View 1 Replies
View Related
Nov 8, 2007
Hi All,
I am using sql server 2005. I stuck out in a strange problem.
I am using view in my stored procedure, when I run the stored procedure some of the rows get skipped out means if select query have to return 10 rows then it is returning 5 rows or any other but not all, also the records displyaing is randomly coming, some time it is displaying reords 12345 next time 5678, other time 2468.
But if I run seperately the querys written in SP then it returns all the rows. Please give me solution why it is happening like this.
There are indexes in the tables.
Once I shrink the database and rebuild the indexes, from then this problem is happening. I have rebuild the indexes several time, also updated the statistics but nothing improving.
But nothing is improving
View 7 Replies
View Related
Jan 3, 2008
I have a table that has a number of columns and rows and I need to run a stored procedure to extract data based on the column name and row name. Can anyone help me?
Many thanks
View 12 Replies
View Related
Nov 3, 2003
In the following stored procedure I would like to test whether @TopCategoryID is null. If so I would like to insert the @CategoryID value into the @TopCategoryID value. So, once @CategoryID recieves the @@IDENTITY value, how do I enter this same value into @TopCategoryID as well???
CREATE PROCEDURE sp_CT_InsertCategory
@Namevarchar(50),
@Description varchar(250),
@topCategory bit,
@ParentCategoryID int,
@TopCategoryID int,
@CategoryID int OUTPUT
AS
DECLARE @CurrID int
IF @CurrID IS NULL
BEGIN
INSERT
INTO CT_Category
(CategoryName, CategoryDescription, topcategory, parentcategoryid, topcategoryid)
VALUES
(@Name, @Description, @topcategory, @ParentCategoryID, @TopCategoryID)
SET @CategoryID = @@IDENTITY
IF @@ERROR > 0
BEGIN
RAISERROR ('Insert of Category failed', 16, 1)
RETURN 99
END
END
ELSE
BEGIN
SET @CategoryID = -1
END
GO
Thanks in advance
View 9 Replies
View Related
Feb 15, 2002
I have the following lines embedded in a stored procedure
---
----
----
select @querystr = "select @lkinpos = pos_lkin_pos from "+@database+" where pos_clnt_id = "+str(@clntid)+" and pos_isin ="+"'"+ @isinno+"'"
print @querystr
exec(@querystr)
---
---
---
When i execute the above stored procedure, it returns an error as follows:
Server: Msg 137, Level 15, State 1, Line 1
Must declare the variable '@lkinpos'.
When i see the print @querystr statement, it returns the query str as follows:
select @lkinpos = pos_lkin_pos from nsdldpm..pos_mstr where pos_clnt_id = 10000045 and pos_isin ='ine227a01011'
This when executed independently, gives me the required output.
Can anybody solve this for me?
Thanks in advance
View 1 Replies
View Related
Jan 11, 2008
Hi, I have an app where I am calling a stored procedure that runs and returns an integer. I would like to assign this integer to a control on the page. Here is a sample of code and below I will give the errors: Protected Sub NewButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles NewButton.Click Dim tempconnection As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("TestConnectionString").ConnectionString) Dim tempproc As New Data.SqlClient.SqlCommand("SP_FetchProviders", tempconnection) Dim tempparam As New Data.SqlClient.SqlParameter tempproc.CommandType = Data.CommandType.StoredProcedure tempproc.Parameters.Add(New SqlParameter("@Agency_ID", Data.SqlDbType.Int)) tempproc.Parameters("@Agency_ID").Value = "8" 'Using a number just to test, will be populated by a session variable later tempparam = tempproc.CreateParameter() tempparam.ParameterName = "@OutValue" tempparam.Direction = Data.ParameterDirection.ReturnValue tempparam.SqlDbType = Data.SqlDbType.Int tempconnection.Open() tempproc.ExecuteNonQuery() Dim labelfill As String labelfill = tempproc.Parameters("@OutValue").Value tempconnection.Close() CType(Me.DetailsView1.FindControl("OmbudINSDDL"), DropDownList).Items.Add(labelfill) 'This is inside of a detailsview templatefield End Sub Here is the stored procedure set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgoALTER procedure [dbo].[SP_FetchProviders] @Agency_ID intas Select Name, ProviderSubUnit_ID From ProviderSubunit a join Ombudsman b on a.contractproviders_id=b.contractproviders_id Where b.agency_id = @Agency_ID Order by Name This takes the @Agency_ID as input variable, and has returns an integer (according to SQL management studio). When I try to run my code I get the error that an sqlparameter with parametername @OutValue is not contained by this sqlparametercollection. This may be a simple question, but does the outvalue have to be declared in the stored procedure? If so, can you provide the right syntax? If not, can you offer a suggestion to populate the dropdownlist with the returned value? Thanks in advance.
View 3 Replies
View Related
Sep 27, 2007
Hey all,
i have a question for all the SQL Gurus out there. I have tried to think of a way around, it, but i cannot work it out.
I have a set of data: Samples Below:
Item Warehouse FOR1 FOR2 FOR3 FOR4 FOR5 FOR6 FOR7 FOR8 FOR9 FOR10 FOR11 FOR12 FOR13 FOR14
01-0001 010 329 329 335 343 317 331 328 331 31
I have written a Query to Pivot this data like below:
SELECT WAREHOUSE,ITEM, QTY
FROM
(SELECT ITEM,WAREHOUSE,FOR1,FOR2,for3,for4,for5,for6,for7,for8,for9,for10,
for11,for12,for13,for14,for15,for16,for17,for18,for19,for20,for21,
for22,for23,for24 FROM mvxreport.tbldmsForecasttoMovex) p
UNPIVOT
(QTY FOR tbldmsForecasttoMovex IN (FOR1,FOR2,for3,for4,for5,for6,for7,
for8,for9,for10,for11,for12,for13,for14,for15,for16,for17,for18,for19,
for20,for21,for22,for23,for24))AS unpvt
Warehouse Item Qty
010 01-0001 329
010 01-0001 329
010 01-0001 335
010 01-0001 343
010 01-0001 317
010 01-0001 331
010 01-0001 328
010 01-0001 331
010 01-0001 315
010 01-0001 344
010 01-0001 334
010 01-0001 321
010 01-0001 327
010 01-0001 328
010 01-0001 332
010 01-0001 342
010 01-0001 316
010 01-0001 330
010 01-0001 330
010 01-0001 331
010 01-0001 315
010 01-0001 343
010 01-0001 333
010 01-0001 322
I would like to add some more code to the query, so for each FOR% column,
i can put a numeric value in it. The value will be the numbers ,1 - 24 . One for each line as this represents Months Forward.
Example:
Warehouse Item Qty Month
010 01-0001 329 1
010 01-0001 329 2
010 01-0001 335 3
010 01-0001 343 4
010 01-0001 317 5
010 01-0001 331 6
010 01-0001 328 7
010 01-0001 331 8
010 01-0001 315 9
010 01-0001 344 10
010 01-0001 334 11
010 01-0001 321 12
010 01-0001 327 13
010 01-0001 328 14
010 01-0001 332 15
010 01-0001 342 16
010 01-0001 316 17
010 01-0001 330 18
010 01-0001 330 19
010 01-0001 331 20
010 01-0001 315 21
010 01-0001 343 22
010 01-0001 333 23
010 01-0001 322 24
Does anyone know how i can do this?
Many Thnank
Scotty
View 5 Replies
View Related
May 4, 2007
hi ,
i got this error ... i have tried various scenarios.. nothing works for me... can any one gimme the proper guidance...
The variable name '@CCSID' has already been declared. Variable names must be unique within a query batch or stored procedure.
thanx in advance
raj
View 5 Replies
View Related
May 14, 2008
Hello,
I have a stored procedure where I run an insert statement. I want to knwo if it is possible to do it using a variable for the table name (either in-line or with an EXEC statement without building a string first and executing that string. See examples of what I am talking about in both cases below:
I want to be able to do this (with or without the EXEC) :
------------------------------------------------------------------------------------
DECLARE @NewTableNameOut as varchar(100)
Set @NewTableNameOut = 'TableToInsertInto'
EXEC(
Insert Into @NewTableNameOut
Select * From tableToSelectFrom
)
------------------------------------------------------------------------------------
I can not do the above because it says I need to declare/set the @NewTableNameOut variable (assuming it is only looking at this for the specific insert statement and not at the variable I set earlier in the stored procedure.
I can do it like this by creating a string with the variable built into the string and then executing the string but I want to know if I can do it like I have listed above.
------------------------------------------------------------------------------------
DECLARE @NewTableNameOut as varchar(100)
Set @NewTableNameOut = 'TableToInsertInto'
EXEC(
'Insert Into ' + @NewTableNameOut + ' ' +
'Select * From tableToSelectFrom'
)
------------------------------------------------------------------------------------
It is not an issue for my simple example above but I have some rather large queries that I am building and I want to run as described above without having to build it into a string.
Is this possible at all?
If you need more info please let me know.
View 1 Replies
View Related
Feb 27, 2008
I'm new to SSIS, but have been programming in SQL and ASP.Net for several years. In Visual Studio 2005 Team Edition I've created an SSIS that imports data from a flat file into the database. The original process worked, but did not check the creation date of the import file. I've been asked to add logic that will check that date and verify that it's more recent than a value stored in the database before the import process executes.
Here are the task steps.
[Execute SQL Task] - Run a stored procedure that checks to see if the import is running. If so, stop execution. Otherwise, proceed to the next step.
[Execute SQL Task] - Log an entry to a table indicating that the import has started.
[Script Task] - Get the create date for the current flat file via the reference provided in the file connection manager. Assign that date to a global value (FileCreateDate) and pass it to the next step. This works.
[Execute SQL Task] - Compare this file date with the last file create date in the database. This is where the process breaks. This step depends on 2 variables defined at a global level. The first is FileCreateDate, which gets set in step 3. The second is a global variable named IsNewFile. That variable needs to be set in this step based on what the stored procedure this step calls finds out on the database. Precedence constraints direct behavior to the next proper node according to the TRUE/FALSE setting of IsNewFile.
If IsNewFile is FALSE, direct the process to a step that enters a log entry to a table and conclude execution of the SSIS.
If IsNewFile is TRUE, proceed with the import. There are 5 other subsequent steps that follow this decision, but since those work they are not relevant to this post.
Here is the stored procedure that Step 4 is calling. You can see that I experimented with using and not using the OUTPUT option. I really don't care if it returns the value as an OUTPUT or as a field in a recordset. All I care about is getting that value back from the stored procedure so this node in the decision tree can point the flow in the correct direction.
CREATE PROCEDURE [dbo].[p_CheckImportFileCreateDate]
/*
The SSIS package passes the FileCreateDate parameter to this procedure, which then compares that parameter with the date saved in tbl_ImportFileCreateDate.
If the date is newer (or if there is no date), it updates the field in that table and returns a TRUE IsNewFile bit value in a recordset.
Otherwise it returns a FALSE value in the IsNewFile column.
Example:
exec p_CheckImportFileCreateDate 'GL Account Import', '2/27/2008 9:24 AM', 0
*/
@ProcessName varchar(50)
, @FileCreateDate datetime
, @IsNewFile bit OUTPUT
AS
SET NOCOUNT ON
--DECLARE @IsNewFile bit
DECLARE @CreateDateInTable datetime
SELECT @CreateDateInTable = FileCreateDate FROM tbl_ImportFileCreateDate WHERE ProcessName = @ProcessName
IF EXISTS (SELECT ProcessName FROM tbl_ImportFileCreateDate WHERE ProcessName = @ProcessName)
BEGIN
-- The process exists in tbl_ImportFileCreateDate. Compare the create dates.
IF (@FileCreateDate > @CreateDateInTable)
BEGIN
-- This is a newer file date. Update the table and set @IsNewFile to TRUE.
UPDATE tbl_ImportFileCreateDate
SET FileCreateDate = @FileCreateDate
WHERE ProcessName = @ProcessName
SET @IsNewFile = 1
END
ELSE
BEGIN
-- The file date is the same or older.
SET @IsNewFile = 0
END
END
ELSE
BEGIN
-- This is a new process for tbl_ImportFileCreateDate. Add a record to that table and set @IsNewFile to TRUE.
INSERT INTO tbl_ImportFileCreateDate (ProcessName, FileCreateDate)
VALUES (@ProcessName, @FileCreateDate)
SET @IsNewFile = 1
END
SELECT @IsNewFile
The relevant Global Variables in the package are defined as follows:
Name : Scope : Date Type : Value
FileCreateDate : (Package Name) : DateType : 1/1/2000
IsNewFile : (Package Name) : Boolean : False
Setting the properties in the "Execute SQL Task Editor" has been the difficult part of this. Here are the settings.
General
Name = Compare Last File Create Date
Description = Compares the create date of the current file with a value in tbl_ImportFileCreateDate.
TimeOut = 0
CodePage = 1252
ResultSet = None
ConnectionType = OLE DB
Connection = MyServerDataBase
SQLSourceType = Direct input
IsQueryStoredProcedure = False
BypassPrepare = True
I tried several SQL statements, suspecting it's a syntax issue. All of these failed, but with different error messages. These are the 2 most recent attempts based on posts I was able to locate.
SQLStatement = exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
SQLStatement = exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
Parameter Mapping
Variable Name = User::FileCreateDate, Direction = Input, DataType = DATE, Parameter Name = 0, Parameter Size = -1
Variable Name = User::IsNewFile, Direction = Output, DataType = BYTE, Parameter Name = 1, Parameter Size = -1
Result Set is empty.
Expressions is empty.
When I run this in debug mode with this SQL statement ...
exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
... the following error message appears.
SSIS package "MyPackage.dtsx" starting.
Information: 0x4004300A at Import data from flat file to tbl_GLImport, DTS.Pipeline: Validation phase is beginning.
Error: 0xC002F210 at Compare Last File Create Date, Execute SQL Task: Executing the query "exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output" failed with the following error: "No value given for one or more required parameters.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Compare Last File Create Date
Warning: 0x80019002 at GLImport: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "MyPackage.dtsx" finished: Failure.
When the above is run tbl_ImportFileCreateDate does not get updated, so it's failing at some point when calling the procedure.
When I run this in debug mode with this SQL statement ...
exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
... the tbl_ImportFileCreateDate table gets updated. So I know that data piece is working, but then it fails with the following message.
SSIS package "MyPackage.dtsx" starting.
Information: 0x4004300A at Import data from flat file to tbl_GLImport, DTS.Pipeline: Validation phase is beginning.
Error: 0xC001F009 at GLImport: The type of the value being assigned to variable "User::IsNewFile" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
Error: 0xC002F210 at Compare Last File Create Date, Execute SQL Task: Executing the query "exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output" failed with the following error: "The type of the value being assigned to variable "User::IsNewFile" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Compare Last File Create Date
Warning: 0x80019002 at GLImport: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "MyPackage.dtsx" finished: Failure.
The IsNewFile global variable is scoped at the package level and has a Boolean data type, and the Output parameter in the stored procedure is defined as a Bit. So what gives?
The "Possible Failure Reasons" message is so generic that it's been useless to me. And I've been unable to find any examples online that explain how to do what I'm attempting. This would seem to be a very common task. My suspicion is that one or more of the settings in that Execute SQL Task node is bad. Or that there is some cryptic, undocumented reason that this is failing.
Thanks for your help.
View 5 Replies
View Related
Jul 19, 2012
I don't know if it's a local issue but I can't use temp table or table variable in a PP query (so not in a stored procedure).
Environment: W7 enterprise desktop 32 + Office 2012 32 + PowerPivot 2012 32
Simple example:
declare @tTable(col1 int)
insert into @tTable(col1) values (1)
select * from @tTable
Works perfectly in SQL Server Management Studio and the database connection is OK to as I may generate PP table using complex (or simple) queries without difficulty.
But when trying to get this same result in a PP table I get an error, idem when replacing table variable by a temporary table.
Message: OLE DB or ODBC error. .... The current operation was cancelled because another operation the the transaction failed.
View 11 Replies
View Related
Mar 8, 2005
Consider the following:
Sub regUser(s as Object, e as EventArgs)
If IsValid Then
Dim stuTable as String
Dim connStr as String
stuTable = "mytable"
connStr = "myConnectionInfo"
'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)
connect.Open()
strDbResult = cmdSelect.ExecuteReader()
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
'declare stuFname, stuLname, stuEmail
stuFName = strDbResult("stu_fname")
stuLName = strDbResult("stu_lname")
stuEmail = txtStdEmail.text
'more code follows ....
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" ... ??
Sorry, I'm a .NET beginner ...
View 1 Replies
View Related
Feb 4, 2008
Hi,
Is it possible to assign the column value to a user defined variable?
View 3 Replies
View Related
Aug 24, 2007
Hi ,
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?
Thanks
View 13 Replies
View Related
Dec 6, 2006
i am trying on this but hit error
Declare @var int
Set @var = select max(value) from xxx
anyone can help me?
View 2 Replies
View Related
Aug 8, 2006
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.
Thanks in advance for any help
View 3 Replies
View Related
Mar 20, 2008
Hi,
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.
Please suggest me.
Regards,
View 10 Replies
View Related
Oct 25, 2004
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?
Thanks
View 2 Replies
View Related
Apr 10, 2008
Hi all,
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.
Could someone give me a hint to handle this?
Thanks in advice!
Cheers
Markus
View 3 Replies
View Related
Apr 3, 2008
Hi all!!!
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!!
PLEASE HELP!!
View 4 Replies
View Related
Aug 12, 2006
I am getting wrong output when assigning a datepart function to a variable. I should get 2006 but instead I get an output 1905.
Below is the code and output. Any help will be greatly appreciated. Thanks
DECLARE @FiscalStartCurrYear datetime
SET @FiscalStartCurrentYear = DATEPART(year, GETDATE())
select @FiscalStartCurrYear
Output
-----------
1905-06-30 00:00:00.0000
View 5 Replies
View Related
Jan 31, 2007
Hello,
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.
Thanks,
Phil
View 15 Replies
View Related
Mar 27, 2006
Hello to all!
I have a table name stored in a scalar variable (input parameter of my stored procedure). I need to run SQL statement: SELECT COUNT (*) FROM MyTable and store the result of my query in a scalar variable:
For example:
declare @countRows int
set @countRows = (select count(*) from MyTable)
The problem is that the name of MyTable is stored in the input variable of my stored procedure and of corse this does not work:
declare @countRows int
set @countRows = (select count(*) from @myTableName)
I also tried this:
declare @sqlQuery varchar(100)
set @sqlQuery = 'select count(*) from ' + @myTableName
set @countRows = exec(@sqlQuery)
But it looks like function exec() does not return any value...
Any idea how to solve this problem?
Thanx,
Ziga
View 3 Replies
View Related
Apr 20, 2007
I'm using SSEE 9.0.3042 and started loosing sleep over trying to figure out why the following piece of SQL
DECLARE @x xml
DECLARE @a nvarchar(400);
DECLARE @b nvarchar(400);
DECLARE @c nvarchar(400);
SET @x=N'<SuchKriterienDataSet xmlns="http://tempuri.org/SuchKriterienDataSet.xsd">
<SuchKriterien><Index>0</Index><Name>a</Name><Wert>Test1</Wert><Bedingung>0</Bedingung></SuchKriterien>
<SuchKriterien><Index>1</Index><Name>b</Name><Wert>Test2</Wert><Bedingung>0</Bedingung></SuchKriterien>
<SuchKriterien><Index>2</Index><Name>c</Name><Wert>Test3</Wert><Bedingung>0</Bedingung></SuchKriterien>
</SuchKriterienDataSet>';
WITH XMLNAMESPACES ('http://tempuri.org/SuchKriterienDataSet.xsd' AS ds)
SELECT
@a=@x.value('(/dsuchKriterienDataSet/dsuchKriterien/ds:Wert[../ds:Name = "a"])[1]','nvarchar(400)'),
@b=@x.value('(/dsuchkriterienDataSet/dsuchkriterien/ds:Wert[../ds:Name = "b"])[1]','nvarchar(400)'),
@c=@x.value('(/dsuchKriterienDataSet/dsuchKriterien/ds:Wert[../ds:Name = "c"])[1]','nvarchar(400)');
WITH XMLNAMESPACES ('http://tempuri.org/SuchKriterienDataSet.xsd' AS ds)
SELECT
@x.value('(/dsuchKriterienDataSet/dsuchKriterien/ds:Wert[../ds:Name = "a"])[1]','nvarchar(400)'),
@x.value('(/dsuchKriterienDataSet/dsuchKriterien/ds:Wert[../ds:Name = "b"])[1]','nvarchar(400)'),
@x.value('(/dsuchKriterienDataSet/dsuchKriterien/ds:Wert[../ds:Name = "c"])[1]','nvarchar(400)')
UNION ALL
SELECT @a,@b,@c
returns
Test1 Test2 Test3
Test1 NULL Test3
instead of
Test1 Test2 Test3
Test1 Test2 Test3
This is the shortest repro I could assemble. Once you increase the number of variables, a random pattern of dropped values emerges.
I could repro on fully patched Windows XP German w/ SSEE ENU and Windows Server 2003 64-bit w/ SSEE GER.
Any workaround highly appreciated.
Thx,
Henry
View 5 Replies
View Related
Jun 12, 2007
Hey all!
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?
Thanks for any suggestions!
Jim Work
View 5 Replies
View Related
Oct 15, 2015
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.
View 2 Replies
View Related
Nov 15, 2007
do i need to nest a query in RS if i want a calculated column to be compared against a multi value variable? It looks like coding WHERE calcd name in (@variable) violates SQL syntax. My select looked like
SELECT ... ,CASE enddate WHEN null then 1 else 0 END calcd name
FROM...
WHERE ... and calcd name in (@variable)
View 1 Replies
View Related
Sep 28, 2005
In my Script Component properties I have included "ClientReportGroupId" as a ReadWrite variable. This variable is declared as a Package Variable.
View 23 Replies
View Related
Jul 10, 2006
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
(Me.Variables.gsFilename.ToString),(Me.Variables.giRowCount.ToString)
-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
Thanks in advance Dave
Imports System
Imports System.Data
Imports System.Math
Imports System.IO
Imports System.Text
Imports System.Configuration
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
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)
sbRecord.Append(Row.ProjectID.ToString)
sbRecord.Append(Row.TransactionRefNum.ToString)
sbRecord.Append(Row.BillToCustomerNum.ToString)
sbRecord.Append(Row.BillToAccountNum.ToString)
sbRecord.Append(Row.BillToLineNum.ToString)
sbRecord.Append(Row.BillToReassignmentNum.ToString)
sbRecord.Append(Row.ChargeCode.ToString)
sbRecord.Append(Row.NotificationMethod.ToString)
sbRecord.Append(Row.AdjustmentAmount.ToString)
sbRecord.Append(Row.AdjustmentDate.ToString)
sbRecord.Append(Row.ReparationGivenFlag)
sbRecord.Append(Row.BillingSystemProcessingErrorCode.ToString).Append(vbNewLine)
End Sub
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)
'Close file
sw.Close()
End Sub
End Class
Has anyone got a workaround
thanks in advance
Dave
View 6 Replies
View Related