Access SQL: creating field at runtime - sql

I'm trying to create a "dynamic" field in my SQL query
INSERT INTO tblCARS (CreateField("[tblCARS]","[colors]","TEXT"))
SELECT avail_colors
FROM tblSHOPS
WHERE car_model = model_car;
This should give me the same result as
INSERT INTO tblCARS (colors)
SELECT avail_colors
FROM tblSHOPS
WHERE       car_model = model_car;
The field [colors] does not exist, so i want to append it to the existing table called [tblCARS] when i run the query.
The function CreateField() looks like this
Public Function CreateField(strTable As String, strField As String, strType As String) As Variant
CreateField = Null
If (strField <> vbNullString) And (DoesTblFieldExist(strTable, strField) = False) Then
CurrentDb.Execute "ALTER TABLE " & strTable & " ADD COLUMN " & strField & " " & strType
End If
CreateField = strField
End Function
When i run the query, Access gives me the error "incorrect syntax" (translated) and the cursor stops at the second parenthesis.
Have anyone succeeded with creating fields at runtime on a Access query?
I know i could do this entirely on VBA, but that is not my goal.
Any hints?

That approach attempts to have the db engine determine the name of the destination field when the statement is executed. Unfortunately, Access' db engine does not provide that capability.
Essentially, the statement treats that CreateField() function as a parameter. And Access won't let you use a parameter for a field name.
Consider a straightforward parameter example. This statement succeeds ...
INSERT INTO tblFoo(some_text) VALUES ("bar");
But when providing the same field name (some_text) as a parameter, the statement fails ...
PARAMETERS which_field Text ( 255 );
INSERT INTO tblFoo(which_field) VALUES ("bar");
So you'll need to use 2 operations instead of a single query. You could execute the ALTER TABLE and then a revised INSERT with the field name hard-coded into the statement.

Related

Replacing String for entire Column

I am new to MS ACCESS & SQL
I am trying to replace all the "[" & "]" within the table.
Am I suppose to use REPLACE command or should Select & Loop through the Table?
Either way, I don't know how to write it in VBA. Thanks for help
I tried this, and it is not working
DoCmd.RunSQL "SELECT REPLACE" & "(StudentFirstName,'[','')" & "FROM StudentName"
See the Table Structure:
Just run an UPDATE query with REPLACE() function:
UPDATE tableName SET fieldName = REPLACE(fieldName, '[', '')
and than with the other bracket:
UPDATE tableName SET fieldName = REPLACE(fieldName, ']', '')
If you want to use in your vba code:
Docmd.RunSQL "UPDATE tableName SET fieldName = REPLACE(fieldName, '[', '')"
Docmd.RunSQL "UPDATE tableName SET fieldName = REPLACE(fieldName, ']', '')"
Remember: SELECT it's used only for VIEW data and not for edit.
If you want to EDIT data in your table you need to use UPDATE.

How to put SQL query in Spring boot application in if function?

In my spring boot application in REQUEST i post streamName and in response I get key. I'm putting this into a database and I want to avoid repeating stream names. My plan is to add such query to the insertStream method and when it returns null value, i.e. there is no such name in the database, then INSERT will be performed. Unfortunately I do not know how to implement this in the code.
This is my method:
#Override
public int insertStream(String key, String streamName) {
String sql = "" +
"INSERT INTO stream (" +
" stream_name, " + " license_key )" + "VALUES (?,?)";
return jdbcTemplate.update(
sql,
streamName,
key
);
}
and this is mention example query:
SELECT count(*) FROM public.stream WHERE stream_name='live2';
but instead of live2 it will be streamName parameter
you can use upsert in postgrsql
add a unique constraint to the stream_name column
CREATE UNIQUE INDEX unq_stream_name on stream(stream_name);
ALTER TABLE stream
ADD CONSTRAINT unq_stream_name_const
UNIQUE USING INDEX unq_stream_name;
then do upsert:
insert into stream (stream_name, license_key)
values (?,?) on conflict do nothing;
if the stream_name already exists , nothing will be inserted.

How to insert special characters to a table row via SQL Editor

I have a table in my SQL Server database with a column of type nvarchar(50);
I tried to do this:
Right click on my table
Selecting "Edit 200 first rows"
Typing in that column 'a'
I get an error like this:
Error source: .Net SqlClient Data Provider.
Error message: Incorrect syntax near 'a'.
Correct the errors and retry".
Why do I get this error message and how can I fix this?
I have used aqua data studio and tested this it is allowing me.
my result:::
id testc
----- ---------
1 'asdfasd'
If you want to use it thrugh .net then while passing the string add the escape sequences. suppose if you are sending "'"--single quote.. then send I have used and tested this it like "\'" is allowing me.
refer below link:::
http://www.codeproject.com/Questions/157918/How-can-I-insert-a-special-character-in-sql-server
I have had the same error.
I want to insert a value I am Nam 'ABC' into MyTable at field Description as following SQL statement
Insert Into table MyTable (Description) values('I am Nam 'ABC'');
Once Insert command executed the error occur immediately
Incorrect syntax near 'ABC'.
Note that the reason why is SQL will understand character " ' " which before ABC belongs to character
" ' " before I, and one after ABC belongs to " ' " at the end. As a result ABC does not belong to SQL
statement anymore therefore it makes a break of statement.
Here is my solution:
I added two single quotes for each side of ABC
Insert Into table MyTable (Description) values('I am Nam ' 'ABC' ' ');

Order by in for loop (SQL UDF)

I want to aggregate some rows using a SQL UDF. I want to first select the rows ordered by their id & then concatenate them in a comma separated column. I am having error on the order by clause in my function as it is inside a for loop. Is there any way to run this without removing the order by clause? My database is DB2
CREATE FUNCTION mySchema.getDates(recId INTEGER)
RETURNS VARCHAR(1024)
LANGUAGE SQL
BEGIN ATOMIC
DECLARE STR VARCHAR(1024);
SET STR = '' ;
LOOP1 : FOR ROW AS (select replace(char(myDate,EUR),'.','/') as myDate from myTable.BookingDates where recId=recId order by rec_crt-id)
DO
IF ROW.myDate IS NOT NULL THEN
SET STR = STR || CAST ( ROW.myDate AS VARCHAR ( 20 ) ) || ', ' ;
END IF ;
END FOR;
RETURN STR ;
END
SQL State: 42601
Vendor Code: -199
Message: [SQL0199] Keyword ORDER not expected. Valid tokens: ) UNION EXCEPT. Cause . . . . . : The keyword ORDER was not expected here.
This is not going to work:
where recId=recId
DB2 will not realize that you want one of these to be the function parameter and the other the column name. It will use the same one for both, having the effect of returning all rows. You need to name your function parameter something different than the column name.
Other than that, code similar to the above works fine for me.
Are you new to writing functions? One common mistake is having your SQL editor's statement delimiter set to ;. This will make it try to break up the function into statements, rather than sending the whole thing as a single command. It will lead to lots of syntax errors such as above (Sorry if you know that already, but it took me awhile to figure that out!).

error updating row in postgres table

My table is:
CREATE TABLE A(
id serial NOT NULL,
date timestamp without time zone,
type text,
sub_type text,
filename text,
filepath text,
filesize integer,
);
I have an update routine:
$Query = "UPDATE A SET type=\"" . $strType . "\" where id=" . intval($ID);
Problem:
When $strType is a string, like "lettuce" I get this error:
ERROR: column "lettuce" does not exist
When it is an int, no error.
Ideas?
more background:
the insert code adds filename,filepath, both text types successfully
In SQL, double-quotes are identifier delimiters. Your UPDATE statement is trying to set the type column to the value of the "lettuce" column, which is an error if there is no column named lettuce.
You want to use single-quotes to delimit a string literal in SQL:
$Query = "UPDATE A SET type='" . $strType . "' where id=" . intval($ID);
See also "Do different databases use different name quote?"
Your coding is open to SQL injection. Use placeholders (probably unquoted question marks) and pass the value separately. That avoids the problems at XKCD.
Bill has the answer to your immediate problem about column names vs strings.