INSERT variable values into a table - sql-server

I have several variables in an SSIS package that I would like inserting into a table.
example:-
#financialMonth, #Status, #Comments
The Variables have been populated along the way with values based on lookups, filename, dates, etc, and I want to store them in a results table.
Is using the execute SQL task the way to do this ?
Do I need to call a sproc and pass those variales as parameters ?
I've tried putting the following T-SQL into the SQLStatement property
INSERT INTO FilesProcessed
(ProcessedOn, ProviderCode, FinancialMonth,
FileName, Status, Comments)
SELECT GETDATE(), 'ABC' , 201006,
'ABC_201005_Testology.csv',
'Imported','Success'
I tried hardcoding the values above to get it to work
These are the columns on the table I'm inserting into
Column_name Type Computed Length
fileID int no 4
ProcessedOn datetime no 8
ProviderCode nchar no 6
FinancialMonth int no 4
FileName nvarchar no 510
Status nvarchar no 40
Comments nvarchar no 510
This is the Expression code that feeds the SQLStatementSource property
"INSERT INTO FilesProcessed (ProcessedOn, ProviderCode, FinancialMonth,
FileName, Status, Comments) SELECT GETDATE() AS ProcessedOn, '"
+ #[User::providerCode] + "' , "
+ (DT_STR,6,1252)#[User::financialMonth] + ", '"
+ #[User::fileName] + "', 'Imported' AS Status,'Successfully' AS Comments "
Unfortunately I'm missing something, and can't quite get it to work.
The Error message I'm getting is ...
Error: 0xC002F210 at Log entry in
FilesProcessed, Execute SQL Task:
Executing the query "INSERT INTO
FilesProcessed (ProcessedOn,
ProviderCode, FinancialMonth,
FileName, Status, Comments) SELECT
GETDATE(), 'ABC' , 201006,
'DAG_201005_Testology.csv',
'Imported','Successfully'" failed with
the following error: "An error
occurred while extracting the result
into a variable of type (DBTYPE_I2)".
Possible failure reasons: Problems
with the query, "ResultSet" property
not set correctly, parameters not set
correctly, or connection not
established correctly.
Please
a). Advise whether the Execute SQL Task is the way to do what I want to do.
b). Give me any pointers or pitfalls to look out for and check.
Thanks in advance.

OK, here is what I did.
I created an Execute SQL task and configured, thus :-
General Tab
ConnectionType = OLE DB
SQLSourceType = Direct Input
SQLStatement = (left blank)
BypassPrepare = True
ResultSet = None
Parameter Mapping
(none - leave blank)
Result Set
(none - leave blank)
Expressions
SQLStatementSource = "INSERT INTO FilesProcessed (ProcessedOn, ProviderCode, FinancialMonth, FileName, Status, Comments) SELECT GETDATE(), '" + #[User::providerCode] + "' , " + (DT_STR,6,1252)#[User::financialMonth] + ", '" + #[User::fileName] + "', 'Import - Success', '" + #[User::fileComments] + "'"
Then as long as I set up the variables and populate them in the variables window (the Expression editor will not let you save an expression that references a variable that does not exist. Keep notepad handy to store the contents while you go back and edit the variables window, and add new variables in ;)
Build the expression slowly, using the Parse expression button regularly to check.

make sure that the data types of the VALUES match the destination column data types.
see: http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/e8f82288-b980-40a7-83a6-914e217f247d/

A couple of speculative suggestions
The Error message says An error occurred while extracting the result into a variable of type (DBTYPE_I2). But this is a straight insert statement. There shouldn't be a result except for rows affected. Do you have any parameter mappings erroneously set to Output?
What if you try and run the SQL Query from the error message directly in management studio? Does that give you an error?

In the above table definition FinancialMonth as int datatype as
FinancialMonth int no 4
while inseting casting as :
(DT_STR,6,1252)#[User::financialMonth]
I think it's purely a datatype mismatch with the target table definition.

Related

VB.NET, SQL Server and list of dates

I have a query that takes as a parameter a list of dates. In VB.NET the dates are in a string ArrayList and I am using the String.Join() method to get them in a comma delimited list. The problem is when I do that double quotes are put at the start and end of the string and SQL complains about that (I think; see below). How can I get a list of date from a string ArrayList without the quote.
My arraylist contains these values:
'2020-08-30'
'2020-08-27'
'2020-09-28'
'2020-09-09'
'2020-08-31'
'2020-08-29'
when I join them using String.Join(",", sDates) I get the following:
"'2020-08-30','2020-08-27','2020-09-28','2020-09-09','2020-08-31','2020-08-29'"
and when I use that in a parameter query it gets rejected.
comm.Parameters.AddWithValue("#dates", String.Join(",", sDates))
sql contains the following"
...where pj.ProjectName =#projectname And tcd.Date in (#dates)
Exact error I get is
System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Incorrect syntax near ','.
Source=.Net SqlClient Data Provider
Any advice?
This error message:
Incorrect syntax near ','
Is not caused by the way you've done your IN. It is caused by something else, such as a misplaced comma in a select block:
SELECT , a FROM x
^
The way you've done your IN won't work either, because it's conceptually the same as writing this:
SELECT * FROM table WHERE dateColumn IN ('''2000-01-01'',''2000-02-01''')
There is no such date with a string value of '2000-01-01','2000-02-01'.
If you want to use IN in the style you're attempting here, you have to add a parameter per date value and set it up accordingly:
sqlCommand.CommandText = "SELECT * FROM table WHERE dateCol IN("
Dim p = 0
For Each d as DateTime in MyDateList
sqlCommand.CommandText &= "#p" & i & "," 'concat param placeholder on
sqlCommand.Parameters.AddWithValue("#p" & i, d)
i += 1
Next d
sqlCommand.CommandText = sqlCommand.CommandText.TrimEnd(","c) & ")" 'get rid of trailing comma and close the IN brackets
This will generate an sql like
SELECT * FROM table WHERE dateCol IN (#p0,#p1,#p2)
with 3 parameters, and a populated parameters collection. You've already been pointed to Joel's blog about AddWithValue, so I won't repeat it.. But i did want to say that the way you've presented your question implies you have a list of strings, not datetimes. You should definitely make sure your list has DateTimes in, and your db column should be a date based type, not a string based type

"Error 2147217904 No value given for one or more required parameters" When trying to fetch data using "WHERE" where clause in Excel

I am trying to fetch data from Excel (as Database) when I put simple select query "select * from [Sheet1$]" its working fine and retrieve the data from sheet1. but when I put the conditional statement (where or Like) its throws the error "Error 2147217904 No value given for one or more required parameters".
Query Which is throw error ---
"select * from [Sheet1$] WHERE [Sheet1$].[ColName]= User"
OR
"select * from [Sheet1$] WHERE [ColName] = " & ColName_RunTime
OR
"SELECT * FROM [Sheet1$A2:E2] WHERE ColName =Yes"
Thanks in advance for help or solution.
The error is 0x80040E10L DB_E_PARAMNOTOPTIONAL No value given for one or more required parameters. See: https://technet.microsoft.com/en-us/library/ms171852(v=sql.110).aspx
Effectively, as you point out, there's something wrong with how you are supplying the values for your WHERE clause. It appears that you want to supply a string, so, they must be enclosed in single quotes.
"select * from [Sheet1$] WHERE [Sheet1$].[ColName]= 'User' "

Calling procedure with updates and a ResultSet in MyBatis

I want to map a SQL Server stored procedure with MyBatis, using annotations.
#Select(value = "{call sp_cen_obliczcene(" +
"#{wytworId, mode=IN, jdbcType=NUMERIC}, " +
"#{rodzajCenyId, mode=IN, jdbcType=NUMERIC}, " +
"#{walutaId, mode=IN, jdbcType=NUMERIC}, " +
"#{jmId, mode=IN, jdbcType=NUMERIC}, " +
"#{ilosc, mode=IN, jdbcType=DECIMAL}, " +
"#{data, mode=IN, jdbcType=DATE})}")
#Result(property = "kwota", column = "kwota", javaType = BigDecimal.class, jdbcType = JdbcType.DECIMAL)
#Options(statementType = StatementType.CALLABLE)
public DtoCena dajCene(CriteriaCena parametry);
The procedure selects one row - I am interested in one column. Now, I've mapped a procedure before, only I had multiple rows and selected more then one column from them. Everything worked perfectly fine. When I mapped new procedure, in a similar way I got an error:
### The error occurred while setting parameters
### SQL: {call sp_cen_obliczcene(?, ?, ?, ?, ?, ?)}
### Cause: java.lang.NullPointerException
I started the SQL Profiler and saw that the procedure is called properly with the given parameters. I've noticed that the procedure I'm mapping is executing other procedures. They're performing some updates. When I changed my annotation to #Update I got an other error: that Integer cannot be cast to DtoCena type. I changed the return value of the method to Integer and I got no errors but as you can guess it did not return what I was looking for.
The question is, can I map a stored procedure which updates tables AND returns a ResultSet? I can do this using JDBC, but is this possible with MyBatis? Am I doing something wrong when using the #Select annotation?
Looks like the #Update returns the affected row count ...
Anyway, I don't think the issue is related to calling stored procedure, this is merely a mapping issue that would occur with simple select.
You must use #Result annotation inside #Results annotation, otherwise it is ignored.
Here is a simplified, yet functional, code:
#Select("select 'hello' as h, 1 as n from dual")
#Results({
#Result(column="n")
})
Integer test();
Just add a property attribute and change return type to retrieve result into an object.

How to retrieve the value of uniqueidentifier generated while insert in Delphi ADO?

Suppose I generate the PK for my SQL Server DB table with the help of newid() function. In Java I can do something like this:
...
String query = "DECLARE #newGuid uniqueidentifier "+
"SET #newGuid = newid() "+
"INSERT INTO myTable(id, stringval) "+
"VALUES (#newGuid, "Hello") "+
"SELECT uid FROM #newGuid";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
String uid = rs.getString("uid");
But when I try to make that with Delphi+ADO I get stuck cause ADO can either get data from DB (Open method of AdoQuery) or put data to DB (ExecSQL method). So I can't insert new value to the table and get the parameter value afterwards.
You could solve this problem atleast in two ways.
You can put both of your SQL queries into one string (just like you have in your example) and call TADOQuery.Open or TADOQuery.Active := True. it doesn't matter that you have INSERT statement there as long as query returns something.
You can define parameter's direction as pdOutput in ADOQuery.Parameters collection and read value of that parameter after executing the query.
You are treating #newGuid as if it was a table. Your last row in the query should be:
SELECT #newGuid as uid

Sql Server: getting the names of the objects involved in errors [duplicate]

How do I correctly extract specific info from an sql error message number 547?
Info Required:
Table Name
Constraint Name
Column Name
Code:
Try
....
Catch ex As System.Data.SqlClient.SqlException
If ex.Number = 547 Then
End If
End Try
Sample message:
UPDATE statement conflicted with COLUMN CHECK constraint
'CK_Birthdate'. The conflict occurred in database 'Northwind', table
'Employees', column 'BirthDate'.
There is no straight forward way of getting these pieces of information separately.
It all gets concatenated into the error message.
You can use select * from sys.messages where message_id=547 to see the various different language formats of the message that you would need to deal with in order to extract the constituent parts then perhaps use regular expressions with capturing groups based around this information.
In addition to queries, here's a powershell script which wraps the sys.messages queries.
http://blogs.msdn.com/b/buckwoody/archive/2009/04/30/and-the-winner-is-get-sql-server-error-messages-from-powershell.aspx
its true there is no straight way to fix this but I did this insted
var str = sqlException.Message.ToString();
var strlist = str.Split(',', StringSplitOptions.RemoveEmptyEntries);
var streplace = strlist[1];
streplace = streplace.Replace("table \"dbo.", "");
streplace = streplace.Replace("\"", ""); //this will get the data table name
streplace = string.Concat(streplace.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' ');

Resources