How to insert a null value in SQL Server from C++ - c++

I am using an INSERT statement and want to set a field value to null when its not provided and this a little confusing.
The field (call it name) is type nvarchar in SQL Server. It was being set to name ="NULL"; in C++ in the INSERT statement and it appeared as NULL in SQL server (note shows in italic in sql server).
After I changed the INSERT query to become UNICODE compatible and adding N'NULL' per Microsoft documentation, it now appears as 'NULL' in SQL server (not shown in itatic and has extra ' around it ).
What is the different between NULL and 'NULL'? How can I set this field to real NULL when the field value is empty?
Update
From comments sections Adrew mentioned just insert NULL for name field which shows up (null) in SQL server, yet another type.
I ran the following query in SQL management studio itself to find which one is the real null.
SELECT [NAME], [CITY] FROM TABLE WHERE NAME IS NULL
This returns only those items which were set with ASCII "NULL" value. It's even more confusing.

Related

Azure Web Job bad encoding downloaded data from data lake store

Currently, I'm just want to download files from data lake store and store data into my sql database but I have problem with strings that shoudl containt characters like (ę, ą, ć, ł) but it is replaced by (e,a,c,l). Currently I'm tried changing Culture Information and Encoding in Stream Reader but it doesn't give me any better result (still getting replaced characters in my string values). So is there any work around or any place where I can globally set encoding parameters for my app service and web jobs included in web app service?
The issue is not related to WebJob. We could read any special character from any place and write it to another place due to the read and write work at byte level.
strings that shoudl containt characters like (ę, ą, ć, ł) but it is replaced by (e,a,c,l).
What column type did you define for the special characters in your SQL Server? If the column type is char or varchar. It will lost data if you store special characters. Change the column type to nchar or nvarchar will solve this issue.
Here is the test from my side.
Step 1, Define a table using following SQL statement.
CREATE TABLE [dbo].[mytable]
(
[id] INT NOT NULL PRIMARY KEY,
[text1] varchar(50),
[text2] nvarchar(50)
)
Step 2, Insert a row using following SQL statement.
insert into mytable (id, text1, text2) values(1, 'ę, ą, ć, ł', 'ę, ą, ć, ł')
Step 3, Query data from mytable using following SQL statement.
select * from dbo.mytable
Here is the result I got.
According to the result, the value of text1 was changed to 'e,a,c,l' due to the column type is varchar.

How do I Get SQL Text From ColdFusion Service

I've been given a project that uses AngularJS and ColdFusion as a Service. I understand Angular but I've never worked with ColdFusion before. Within the CFFunction Tag in a ColdFusionComponent I have some complex SQL that is being generated. In addition to the actual data being returned from the Service I would like to have the service return the actual text of the SQL executed. Can someone tell me how this can be done?
From the comments
In order to get the SQL statement that was executed you can use the result attribute of the <cfquery> tag. When you include that attribute then ColdFusion will return more information about the query including the SQL statement that was executed. See the docs here under the "usage" section (about midway down the page) for more information.
From the referenced documentation:
The cfquery tag also returns the following result variables in a structure. You can access these variables with a prefix of the name you specified in the result attribute. For example, if you assign the name myResult to the result attribute, you would retrieve the name of the SQL statement that was executed by accessing #myResult.sql#. The result attribute provides a way for functions or CFCs that are called from multiple pages, possibly at the same time, to avoid overwriting results of one call with another. The result variable of INSERT queries contains a key-value pair that is the automatically generated ID of the inserted row; this is available only for databases that support this feature. If more than one record was inserted, the value can be a list of IDs. The key name is database-specific.
Variable name Description
result_name.sql The SQL statement that was executed.
result_name.recordcount Number of records (rows) returned from the query.
result_name.cached True if the query was cached; False otherwise.
result_name.sqlparameters An ordered Array of cfqueryparam values.
result_name.columnList Comma-separated list of the query columns.
result_name.ExecutionTime Cumulative time required to process the query.
result_name.IDENTITYCOL SQL Server only. The ID of an inserted row.
result_name.ROWID Oracle only. The ID of an inserted row. This is not the
primary key of the row, although you can retrieve rows
based on this ID.
result_name.SYB_IDENTITY Sybase only. The ID of an inserted row.
result_name.SERIAL_COL Informix only. The ID of an inserted row.
result_name.GENERATED_KEY MySQL only. The ID of an inserted row. MySQL 3 does not
support this feature.
result_name.GENERATEDKEY Supports all databases. The ID of an inserted row.

Adding support for machine-specific lookups in SQL Server 2012 database

I have to maintain an App with a SQL Server 2012 back end.
There's a database table containing a bunch of
machine parameter settings, one per column.
Each parameter is an nchar(15) type referencing
a type-dependant lookup-table, e.g.
CREATE TABLE L_MachineSettings (
ID uniqueidentifier NOT NULL PRIMARY KEY,
ParentID uniqueidentifier,
IsActive nchar(15) FOREIGN KEY REFERENCES L_YesNo(Constant),
OnTime nchar(15) FOREIGN KEY REFERENCES L_Time(Constant),
Motor1_InitMode nchar(15) FOREIGN KEY REFERENCES L_InitModes(Constant),
...
and so on (nearly 60 parameters are following, some are ref. the same lookup-tables)
...
)
Each lookup table is built like in this example:
CREATE TABLE L_Lookup_YesNo (
Constant nchar(15) PRIMARY KEY,
TargetValue nvarchar(max),
NotSupportedBy nvarchar(max)
)
INSERT INTO L_Lookup_YesNo
(Constant, TargetValue)
VALUES
(N'No', N'0'),
(N'Yes', N'1')
There are several different machine types among whom, some are not capable
of accepting all values of all lookup tables due to their limited hardware specs.
For those, the field NotSupportedBy in the lookup tables is filled with the machine types not
supporting a value, separated by semicolons, e.g.
INSERT INTO L_Lookup_InitModes
(Constant, TargetValue, NotSupportedBy)
VALUES
(N'Standard', N'144A', NULL),
(N'Extended, N'144B', NULL),
(N'ExtendedPlus' N'144Z', N'AU1220;AU1221'),
(N'ExtendedPlusB' N'144D', N'AU1220;AU1221;AU1401')
The machine types itself are defined in a separate table:
CREATE TABLE L_MTypes (
Name nchar(6) PRIMARY KEY,
Comment nvarchar(max)
)
INSERT INTO L_MTypes
(Name, Comment)
VALUES
(N'AU1220', N'Basic Edition'),
...
A L_MachineSettings row is allowed to be only partially implemented
so it can contain NULL values, as long as it's ParentID
property has been set to another row ID containing the missing
parameters.
Also child row values will overwrite those of the parent's row,
so a hierarchic parameter structure can be build by creating a base setting
and adding only differing values for a new setting while referencing
all other values. If a base value is to be changed, the change "falls through" to
it's childs automatically, so XML files, which represent the final format
of the data, shipped to customers are always containing all recent changes.
I'm now challenged with the job of making those column-lookup-values
machine specific, too, while not throwing the existing database layout
on the heap.
So what I need is a way to store more than one lookup value into a settings field,
which would be associated with a machine type. If no specific value for a specific machine
type is available, the general value should be used on export. The machine-specific values
should be taken from the lookup tables, too.
An important thing is: Next to a GUI (written in C++Builder) some users are also
accessing the SQL Server DB via MS Access and those users are not qualified personnel in terms of databases (you know
what I mean), so there should be only minor changes to the existing structure.
My ideas so far:
Adding a new column MType to L_MachineSettings to add machine specific options to the ParentID setting
Adding machine specific values via semicolon-separation to a field, e.g. "Yes;AU1220:No"
While the first idea seems simple at first, I fear the collisions with the ParentID stuff and the probably resulting chaos.
The second approach will give up the existing lookup relationships, (only breaking that with the lookup-tables NotSupportedBy column until now), so I won't accept that change.
Who has some best practices for me, here?

PostgreSQL sequence being reset?

On a regular occasion, my Django webapps produce SQL errors on M2M tables.
Each time it turns out the ID sequence is reset to a value within the range of existing rows.
The app performs normal SQL queries such as:
INSERT INTO "myapp_project" ("name") VALUES ('test1') RETURNING "myapp_project"."id"'
which cause errors such as:
IntegrityError: duplicate key value violates unique constraint "myapp_project_pkey"
DETAIL: Key (id)=(29) already exists.
Then it turns out that the myapp_project_id_seq is pointing to an old ID number:
select currval('myapp_project_id_seq')
29
Which can then be reset by using:
select setval('myapp_project_id_seq', (select max(id) from myapp_project))
However, I can't explain why this is happening. It typically happens on M2M tables in Django. In this case, a normal table with admin-only input. Can someone enlighten me about this?
This typically happens when you (or somebody) sometimes write values to id explicitly, instead of getting values from the sequence (by default or with nextval()).
Your repair code is missing a pair of parentheses.
SELECT setval('myapp_project_id_seq', (SELECT max(id) FROM myapp_project));
This is a tiny bit shorter & cheaper while doing the same, exactly:
SELECT setval('myapp_project_id_seq', max(id)) FROM myapp_project;

MySQL C++ Connector: Get the insert_id

I am using mysql connector C++. There is an auto_increament column in my table, I want to get the insert id when I perform an insert action. Does someone know how to get it? Thanks.
My code is something like:
conn->setAutoCommit(0);
pstmt.reset(conn->prepareStatement(insertStr.c_str()));
int updateCount = pstmt->executeUpdate();
conn->commit();
If the API of the library you are using does not provide a method to retrieve the last_insert_id (which seems to be the case for the C++ Connector) you can always do a query
SELECT LAST_INSERT_ID();
which gives you the "value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement." See here for the explanation of MySQL's documentation
UPDATE:
I found this post from a user who is saying the if you do not use auto_increment on your field you can use
SELECT ##identity AS id;