Incorrect insert syntaxis SQL Server - sql-server-2008

I have created a Temporal Table:
create table #T_Table(id int,name nvarchar(80),value float);
I am executing dynamic SQL to insert to #T_Table the select result from #table_name like this:
SET #template = 'INSERT #T_Table (id,name,value) VALUES('+Cast(#counterI as nvarchar)+', '+ #fieldFromTableName +', Select [value] = SUM('+#fieldFromTableName+') FROM '+ #table_name +')';
EXEC (#template);
So if I print#template:
INSERT #T_Table(id,name,value) VALUES(1, x1, Select [value] = SUM(x1) FROM Mytable);
What is it wrong?

HereĀ“s the INSERT you should build:
INSERT #T_Table(id,name,value)
SELECT 1, 'x1', SUM(x1) FROM Mytable

You can't nest a SELECT inside a VALUES set of values.
Change VALUES to SELECT and get rid of the brackets. You also need to make sure x1 is wrapped in quotes, e.g.:
INSERT #T_Table(id,name,value)
SELECT 1, 'x1', Select [value] = SUM(x1) FROM Mytable;
To get quotes around x1 you will have to put double quotes in your quoted string to escape them: e.g. SET #quotedString = 'not quoted, ''quoted,'' not quoted'

Related

Alias a mysql table for a session?

I know you can give an alias to a table for a query, like SELECT 1 FROM table AS t but is there a way to give an alias to a table for a session?
The use case is I have a "query pattern" that should apply to 3 different tables. So I would like to make only one query, using a table alias, and then tell mysql "Execute this query considering that is alias is table1, then execute the same query considering the alias is table2,..."
The use case:
INSERT INTO aliasedTable (id, value) VALUES (1,1)
The tables
CREATE TABLE table1 (id INT UNSIGNED, value TINYINT UNSIGNED)
CREATE TABLE table2 (id INT UNSIGNED, value TINYINT UNSIGNED)
CREATE TABLE table3 (id INT UNSIGNED, value TINYINT UNSIGNED)
The "supposed" syntax
ALIAS table1 AS aliasedTable;
INSERT INTO aliasedTable (id, value) VALUES (1,1)
ALIAS table2 AS aliasedTable;
INSERT INTO aliasedTable (id, value) VALUES (1,1)
ALIAS table3 AS aliasedTable;
INSERT INTO aliasedTable (id, value) VALUES (1,1)
What I thought of, is making a updatable VIEW of the table, but there is no such thing like CREATE TEMPORARY VIEW .... And using a CREATE TEMPORARY TABLE aliasedTable AS (SELECT * FROM table1) would create a table copy, instead of inserting in the original table.
Any suggestion?
Note that I have such case in a PHP code, but also in a procedure:
<?php
$query = 'INSERT INTO aliasedTable (id, value) VALUES (1,1)';
foreach (array('table1', 'table2', 'table3') AS $t) {
// Ideally, I would like to avoid string concat here and tell MySQL
// something like 'ALIAS :placeholder AS aliasedTable', ['placeholder' => $t]
$pdo->query('ALIAS ' . $table1 . ' AS aliasedTable');
$pdo->query($query);
}
or
SET #tables := '["table1","table2","table3"]';
SET #i := JSON_LENGTH(#tables) - 1;
WHILE (#i >= 0) DO
SET #table := JSON_UNQUOTE(JSON_EXTRACT(#tables, CONCAT('$[', #i, ']')));
ALIAS #table AS aliasedTable;
CALL inserting();
SET #i := #i - 1;
END WHILE;
where
CREATE PROCEDURE inserting()
BEGIN
INSERT INTO aliasedTable (id, value) VALUES (1, 1);
END$$
One thing that you could do is switch to a dynamic SQL statement and pass the table name as an input argument to the inserting function:
CREATE PROCEDURE inserting( IN tbl_name VARCHAR(25) )
BEGIN
SET #stmt = CONCAT('INSERT INTO ', tbl_name, ' (id, value) VALUES (1, 1)');
PREPARE stmt FROM #stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Depending on your call this will insert data to appropriate table. As an example:
CALL inserting('table1');
will execute following statement:
INSERT INTO table1 (id, value) VALUES (1,1);
Then from PHP you could call this procedure for each element in your array passing the current element as an argument to the function.

SELECTing the column names for another SELECT - possible?

I have a table t1 with a 'foo' column, and records containing 'bar' and 'baz' in column 'foo'. I also have a table t2 with columns 'bar', 'baz' and 'quux'. I want to do something like the following:
SELECT (SELECT foo from t1) FROM t2;
that is, get the two column names from t1 and query those columns of t2. If I try to do this with MonetDB, I get an error message:
cardinality violation (2>1)
so,
is there some other way to do this with MonetDB?
is this possible in MySQL? other DBMSes?
Example queries (or non-query directives followed by a query) are welcome.
first you need to select the columns into a variable and then use that variable to get tables
something like the following (it is not the actual implementation)
declare #colname varchar(250)
select #colname=foo from t1
select #colname from t2
this may be help.
This is how you can accomplish it in SQL Server
-- Create #T1 which contains names of columns and #T2 which contains the actual columns
CREATE TABLE #T1(colname nvarchar(max))
INSERT INTO #T1 (colname) VALUES ('b')
INSERT INTO #T1 (colname) VALUES ('c')
CREATE TABLE #T2(a int IDENTITY(1,1), b DATETIME DEFAULT GETDATE(), c NVARCHAR(max) DEFAULT 'blah')
INSERT INTO #T2 DEFAULT VALUES
INSERT INTO #T2 DEFAULT VALUES
INSERT INTO #T2 DEFAULT VALUES
--#dSQL will contain the actual SQL string to be executed
DECLARE #dSQL nvarchar(max) = ' '
SELECT #dsql = CONCAT(#dsql,'[',colname,'],') FROM #T1
SELECT #dsql = CONCAT('SELECT',LEFT(#dsql,LEN(#dsql)-1),' FROM #T2')
--You can see the SQL query being executed
PRINT #dsql
--Actually execute it
exec sp_executesql #dsql
MS Sql dynamic sql example.
create table t1(foo varchar(100))
insert t1(foo)
values('bar,baz');
create table t2(bar int, baz int)
insert t2 (bar, baz)
values
(1,100),
(3,300);
declare #cmd varchar(max);
select #cmd= 'select '+ (select top(1) foo from t1) + ' from t2';
EXEC (#cmd);
Result
bar baz
1 1 100
2 3 300
Or may be foo contains column names in different rows, not exactly clear from your question.
create table t1(foo varchar(100))
insert t1(foo)
values('bar'),('baz');
create table t2(bar int, baz int)
insert t2 (bar, baz)
values
(1,100),
(3,300);
declare #cmd varchar(max);
select #cmd= 'select '+ stuff((select ','+ foo from t1 for xml path('')),1,1,'') + ' from t2';
EXEC (#cmd);

Insert MySQL Query with use of concat

Im trying to insert a query to my database using a name in a variable and also using a name in the values. So i want to make it in to 1 name.
Here is an example
SET #name = "This is my";
INSERT INTO mytable (id, name)
VALUES (1, #name + "Test Query");
So, This query should then insert a row with id 1 and name "This is my Test Query" But it gives me an error. Truncated incorrect DOUBLE value: 'Test Query'
You can't use #name + "Test Query" syntax instead you shoud use concat() mysql function see here for more info:http://www.w3resource.com/mysql/string-functions/mysql-concat-function.php
SET #name = "This is my";
INSERT INTO `names` (id, name)
VALUES (1, concat(#name, 'Test Query'));
also make sure that your id is not autoincreament if it is then no need to pass id number in your query like this
INSERT INTO `names` (name)
VALUES (concat(#name, 'Test Query'));
i found no error in sql.. it executed without error..
DECLARE #name as varchar(100)
DECLARE #mytable as table ( id int, [name] varchar(100))
SET #name = 'This is my';
INSERT INTO #mytable (id, name)
VALUES (1, #name + 'Test Query');
Select * from #mytable

sql server stored procedure IN parameter

In SQL Server, I am passing String as parameter :
#Param1 = Test,Test1,Test2
I am formatting it to:
#Param1 = 'Test','Test1','Test2'
When I am trying to use this in SELECT statement with IN parameter, it is not returning any data
SELECT * FROM TABLE1 where COLUMN1 IN (#Param1)
What is the correct syntax?
As pointed out already in the comments by marc_s, IN requires a list of values not simply one variable.
But you could provide those values in a SELECT from a simple table variable like this:
DECLARE #Param1 TABLE (Value NVARCHAR(255));
INSERT INTO #Param1 (Value)
SELECT 'Test1'
UNION
SELECT 'Test2'
UNION
SELECT 'Test3'
SELECT
*
FROM TABLE1
WHERE
COLUMN1 IN
(SELECT Value FROM #Param1)
I wish there were array vars like that! :-)
But you can convert it to a table using a function, and then use the table with your IN clause as you're attempting.
Here is how that would look:
DECLARE #Param1 nvarchar(max)
SET #Param1 = 'Test,Test1,Test2'
SELECT *
FROM myTable
WHERE myField In (Select ParsedString From dbo.ParseStringList(#Param1))
And here is (at least one way to write) the function:
CREATE Function [dbo].[ParseStringList] (#StringArray nvarchar(max) )
Returns #tbl_string Table (ParsedString nvarchar(max)) As
BEGIN
DECLARE #end Int,
#start Int
SET #stringArray = #StringArray + ','
SET #start=1
SET #end=1
WHILE #end<Len(#StringArray)
BEGIN
SET #end = CharIndex(',', #StringArray, #end)
INSERT INTO #tbl_string
SELECT
Substring(#StringArray, #start, #end-#start)
SET #start=#end+1
SET #end = #end+1
END
RETURN
END

SQL INSERT into MySQL table where column name includes an apostrophe

Does anyone know how I can perform an SQL INSERT operation into a MySQL table where column names include apostrophes, for example:
INSERT INTO MYTABLE (`id`, `Column'1`, `Column'2`) VALUES...
I have tried things like this but to no avail:
INSERT INTO MYTABLE (`id`, `Column''1`, `Column''2`) VALUES...
INSERT INTO MYTABLE (`id`, `Column\'1`, `Column\'2`) VALUES...
You should be able to just place backticks around the column name:
INSERT INTO MYTABLE (`id`, `Column'1`, `Column'2`) VALUES...
see SQL Fiddle with Demo
create table yourtable
(
id int,
col1 varchar(10),
`col'2` varchar(10)
);
insert into yourtable (id, col1, `col'2`) values
(1, 'test', 'sdfsd'),
(1, 'test', 'gtet')
Just put the name into a variable and use the character 39 for the apostrophe.
Example :
L'oiseau becomes :
Loiseau = 'L' + chr(39) + 'oiseau'
print(Loiseau)
=> L'oiseau