I'm trying to run this query to insert new row to Users table from my C code using PQexec() (libpq)
INSERT INTO Users
VALUES ((
SELECT MIN(s.id)
FROM generate_series(1,(
SELECT GREATEST(MAX(Id) + 1,1) FROM Users
)) AS s(id)
WHERE NOT EXISTS (SELECT 1 FROM Users WHERE Id = s.id))
, 'Tester', 27)
RETURNING Id;
It performs what i need when i run it in psql terminal, but from C it returns
Error executing query: ERROR: relation "users" does not exist
I checked connection status and it succeeded, using the same user i connect to from terminal. How come it can't find the users table?
EDIT: adding C-code
Connection:
sprintf(connect_param,"host=address dbname=%s user=%s password=%s",
USERNAME, USERNAME, PASSWORD);
conn = PQconnectdb(connect_param);
Query:
sprintf(cmd, "INSERT INTO Users "
"VALUES (( "
"SELECT MIN(s.id) "
"FROM generate_series(1,( "
"SELECT GREATEST(MAX(Id) + 1,1) FROM Users "
" )) AS s(id) "
"WHERE NOT EXISTS (SELECT 1 FROM Users WHERE Id = s.id)) "
" , \'%s\', %d) "
"RETURNING Id;", Name, Age);
res = PQexec(conn,cmd);
I am going for deduction:
Error executing query: ERROR: relation "users" does not exist
This kind of error is throw when the databases doesn't find the table(view, or wathelse can pass through a SELECT, he gives the name of "relation") .So your code looks fine, but a sub-set of reasons can be:
the table users doesn't exists. Some spelling mistake
you perform the query in the wrong database (where this table is not defined)
you perform the query in the wrong server (as above)
you perform the query in the wrong schema (as above)
The string get truncate from the sprintf.
and similar. The connection works very well since you get an answer from the database
your problem of library link to compilation.
gcc -I/usr/include/postgresql/ -L/usr/lib/postgresql/8.3/lib/ -lpq
Related
I am unable to load data from a stage on SnowFlake using java.
I don't see any errors but data is not loaded from stage "mystage" to table "TESTTABLE "
Code:
Connection connection = DriverManager.getConnection(connectionUrl, _connectionProperties);
Statement statement = connection.createStatement();
statement.executeQuery("copy into TESTTABLE (id, name) from (select $1, $2 from #mystage/F.csv.gz t);");
If I run same command in SnowFlake console, data is getting loaded into table "TESTTABLE " properly.
We do not know to which database/schema the default connection points to. I would try to use fully qualified table name:
statement.executeQuery("copy into <db_name>.<schema_name>.TESTTABLE (id, name) from (select $1, $2 from #mystage/F.csv.gz t);");
By mistake I had comment out connection.commit(); that was the problem.
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' "
I have the following query:
SELECT
[tblstudentrakazot].studentid, firstname, lastname, tblRakezetSchedule.*
FROM
tblRakezetSchedule
INNER JOIN
[tblstudentrakazot] ON [tblstudentrakazot].scheduleID = tblRakezetSchedule.scheduleid
INNER JOIN
tblstudents ON [tblstudentrakazot].studentid = tblstudents.studentid
WHERE
scheduleday = datepart(w,convert(datetime,'21/2/2016',103))
AND tblRakezetSchedule.rakezetID = 182
ORDER BY
replace(scheduletimefrom, ':', '')
When run from SQL Server Management Studio, it works perfectly and generates 3 records.
When run from my VBscript app, I get no records
The issue seems to be in the filter that refers to the date scheduleday = datepart(w,convert(datetime,'21/2/2016',103)) - when I comment that out, the query works.
Does anyone know what the issue can be?
I have tried playing with the date settings but that didnt change anything.
I have tried doing CONVERT(int,scheduleday) in the WHERE - that didn't help either, as the scheduleday is already a number format field.
I have tried using dw in the datepart instead of w - also no change.
Thanks in advance
UPDATE:
The query works when I do WHERE CONVERT(int,scheduleday) = 1
Also - I see that CONVERT(int,datepart(w,convert(datetime,'21/02/2016',103))) correctly gives 1 too. Its just weird that 1 <> 1 even when they are both converted to INT
Here is my VBscript:
sql = "SELECT [tblstudentrakazot].studentid, firstname, lastname, tblRakezetSchedule.* FROM tblRakezetSchedule"
sql = sql & " INNER join [tblstudentrakazot] on [tblstudentrakazot].scheduleID = tblRakezetSchedule.scheduleid "
sql = sql & " INNER join tblstudents on [tblstudentrakazot].studentid = tblstudents.studentid"
sql = sql & " WHERE "
sql = sql & " CONVERT(int,scheduleday) = datepart(w,convert(datetime,'" & cleanSQL(planneddate) & "',103)) AND "
sql = sql & " tblRakezetSchedule.rakezetID = " & CleanSQL(x_rakezetID)
sql = sql & " ORDER BY replace(scheduletimefrom, ':', '')"
WHERE:
x_rakezetID = 182
and planneddate is a date variable in the format of `21/02/2016'
The result of SELECT datepart(w,convert(datetime,'21/2/2016',103)) will depend on your session's language settings (which will depend on the user.) For example:
SET LANGUAGE German;
SELECT datepart(w,convert(datetime,'21/2/2016',103)) ;
...returns 7, whereas for English it returns 1.
I therefore suspect that you are using different users or at least different language settings when connection through SSMS versus through your application.
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
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.