I have a carsale project. It completely works on localhost. I have a "AddCar.aspx" page that inserts a car record with car's features. Car features are selected with checkboxes. If i don't check any checkbox, there is no problem. But if i check one of feature checkboxes, my page gives an error like this:
"Subqueries are not allowed in this
context. Only scalar expressions are
allowed."
And my code is like that:
foreach (DataListItem item in Security1.Items) {
CheckBox CheckBox1 = (CheckBox)item.FindControl("CheckBox1");
if (CheckBox1.Checked) {
HiddenField h = (HiddenField)item.FindControl("FeaID");
string add = "Insert into Carfeature (RecID,FeatureID) values ((select Max(RecID) from record),#FeatureID)";
cmd[k] = new SqlCommand();
cmd[k].CommandType = CommandType.Text;
cmd[k].Parameters.Add("#FeatureID", SqlDbType.Int).Value = h.Value;
cmd[k].CommandText = add;
k++;
}
}
Is there any solution?
Two things, first of all, try this SQL:
Insert into Carfeature (RecID,FeatureID)
select Max(RecID), #FeatureID from record;
Secondly, the Max(RecId) is problematic if you have multiple threads doing this. Are you aware that you can get the last inserted identity? Isn't that what you want to do here? If you've just inserted a record into the record table in the previous step
select SCOPE_IDENTITY() as RecID;
will give you the correct RecID in a thread safe manner.
Change your SQL to this:
Insert into Carfeature (RecID,FeatureID)
select Max(RecID), #FeatureID from record
I think you could just re-format your sql and do it this way:
Insert into Carfeature (RecID,FeatureID) select Max(RecID), #FeatureId from record
This is most likely due to concurrency control. A way I'd recommend doing this on SQL Server 2005 is to change your sql statement to the following using CTE's(http://msdn.microsoft.com/en-us/library/ms190766.aspx):
with MaxId as
(
select Max(RecID)
from record
)
insert into Carfeature (RecID,FeatureID)
select #MaxID, #FeatureID
from MaxId
Friends, you all answered true, thanks a lot.
I changed my code like that and it worked:
Insert into Carfeature (RecID,FeatureID) select Max(RecID), #FeatureID from record
But I don't know how to set accepted answer, because all of answers are true :)
Related
I am trying to select the row in a table where the id = user and once I have that row I want to insert into the docId column the value docId. To do this I have tried this:
INSERT INTO (SELECT * FROM users WHERE (id='"+user+"')); (docId) VALUES ('"+docId+"')
but this does not work
I think you want:
update users
set docId = ?
where id = ?
Do not munge the query string with parameter values. These only cause unexpected syntax errors and make the code vulnerable to SQL injection. Learn to use parameters.
Try INSERT INTO TableNmae(SELECT * FROM users WHERE (id='value') and (docId) = ('value1'))
I've tried searching for this particular topic here, but haven't found the answer... Anyway, my aim is to update table (let's call it t_item), specifically column owner_id with values depending on another table (t_item_geo which is in turn linked to t_geo).
I'm not entirely sure whether the syntax below is actually valid for update statements.
UPDATE t_item SET owner_id= 6993 WHERE t_item.owner_id in
(SELECT t_item.owner_id FROM
t_item,
t_item_geo,
t_geo
WHERE
t_item.id = t_item_geo.item_id and
t_item_geo.geo_id = t_geo.id and
t_item.owner_id in (SELECT id FROM t_user WHERE network_id='fffffff') and
t_geo.id in (SELECT id FROM t_geo WHERE full_name = 'yyyyyyy')
);
Anyway, my problem with this query is that it updates far more rows than it should - if I separate just the select statement Oracle returns ~750 rows but the udpate itself updates more than 4000 rows. It's almost as if the condition was completely ignored - which would point me to perhaps incorrect syntax.
I need to update specific value in the table based on the select from few other 'joined' tables. Hope it makes sense.
Thanks for any contribution!
UPDATE: sorry - maybe it wasn't clear from the question itself, but the correct number of edited items should be ~750 and not ~4000. Thanks!
try this
MERGE INTO t_item
USING
(
SELECT t_item.owner_id FROM
t_item,
t_item_geo,
t_geo,
t_item.rowid rowid_sub
WHERE
t_item.id = t_item_geo.item_id and
t_item_geo.geo_id = t_geo.id and
t_item.owner_id in (SELECT id FROM t_user WHERE network_id='fffffff') and
t_geo.id in (SELECT id FROM t_geo WHERE full_name = 'yyyyyyy')
) on (rowid = rowid_sub)
WHEN MATCHED THEN
UPDATE SET owner_id= 6993;
How can I insert data using the select statement...
I have come across a question asking, what is select * from orders; used for?
And the answer was for viewing and inserting ....
Please provide an explanation ...
The answer "for viewing and inserting" is misleading and incomplete; SELECT returns data, which can then be used in almost any SQL statement.
For most normal use cases, you insert data using an INSERT statement.
INSERT INTO MyTable (MyColumn)
VALUES ('MyValue')
In some cases you may want to insert data that you are pulling from another table (or view), in which case you might use this syntax:
INSERT INTO MyTable (MyColumn)
SELECT MyColumn
FROM MyTableOrMyOtherTableOrView
Note that the exact syntax may vary depending upon your database platform.
To insert values based on a select use this syntax:
insert into table1 (mycol)
select mycol from table2
You can also use select into that enables you to create a new table : select into
And select * from table1 means select every column from table1
For a full tutorial on SQL try W3schools
You use
insert into tableX(columnsX) select columnsY from tableY
to insert data from tableY to tableX. They can both be the same. columnsY is a list of columns that exists in tableY and it must match column types in tableY.
That basically means that you'll be inserting existing data into tableX, and that existing data comes from tableY.
For the question,
"what is "select * from orders ;" used for?"
the answer
for viewing and inserting
is not correct. It is only for viewing, not inserting.
private void cnd()
{
SqlConnection con = new SqlConnection("Data Source = serverName;User ID = serverId;Password = serverPassword;Initial Catalog = DatabaseName");
con.Open();
SqlDataAdapter dp = new SqlDataAdapter("SELECT * FROM tableName", con);
SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(dp);
DataSet ds = new DataSet("tableName");
dp.Fill(ds, "tableName");
DataRow dr = ds.Tables["tableName"].NewRow();
dr["columnName"] = "Value";
dr["columnName"] = "Value";
ds.Tables["tableName"].Rows.Add(dr);
int re = dp.Update(ds, "tableName");
Console.WriteLine(re.ToString());
con.Close();
}
Hey, I am using iBATIS with SQL Server Compact Edition 3.5 and try to do a subselect
INSERT INTO FORMINSTANCE (ID, ID_FORM)
SELECT #ID#, f.ID
FROM FORM f
WHERE ID_PROCESS='10804'
When I commit the transaction I get an SqlCeException (SSCE_M_QP_PARAMETERNOTALLOWED).
That the Symbol '#' is on the wrong place. I think this is the #ID# which is unpredicted in SELECT. #ID# is not the name of the column, it's the value that should be inserted into FORMINSTANCE How can i fix this?
ty
If the # part of the column nameā¦
INSERT INTO FORMINSTANCE (ID, ID_FORM)
SELECT [#ID#], f.ID
FROM FORM f
WHERE ID_PROCESS='10804'
If for some odd reason you wanted a dynamic column to be selected at position #1 (not that I really think that this is what you're up to, but anyway), you could get away with:
INSERT INTO FORMINSTANCE (ID, ID_FORM)
SELECT
CASE
WHEN #ID = 'foo' THEN foo
WHEN #ID = 'bar' THEN bar
ELSE NULL
END,
f.ID
FROM
FORM f
WHERE
ID_PROCESS='10804'
I don't think you can if #ID# isn't in the FORM table (ie, a parameter). Even if #ID# was in the standard parameter format of #ID, SQL Server CE doesn't support named parameters in that location.
I'm trying to verify a simple 1 field table to determine if a record exists before inserting a duplicate.
if not exists (select * from url where url = ...)
insert into url...
Can someone Help?
Your code example will run in the full version of SQL, or you could rearrange to the following:
insert into url
select 'myvalue'
where not exists (select * from url where url = 'myvalue')
Just reverse it and add the condition as a where clause predicate
Insert Into Table ....
Where Not Exists
(Select * From table where ...)
... But your basic problem sounds like it might be better solved by putting a alternate key (unique) constraint on the insert table, referencing the url column (I assume Sql CE does Referential Integrity (RI) constraints?)
You might want to read this thread. performing-insert-or-update-upsert-on-sql-server-compact-edition
In a nutshell a sqlce specific solution (using SqlCeResultSet) will provide the maximum performance.
Use an Outer Join
Insert into X(...)
select blah, blah, blah
from
table t left outer join
X on t.id=x.id
where
x.id is null
Granted, this is way past the posting date, but since I've not seen this answered elsewhere in my quick Google search, I thought I'd share how I solved this with SQL CE so others searching might find an answer.
-- Update existing record's value
UPDATE myTable SET myValue = 'Hello World' WHERE keyField = 'MyKey';
-- Insert new record if existing record doesn't exist`
INSERT INTO myTable (keyField, myValue)
SELECT I.keyField, I.myValue
FROM (
SELECT 'Hello World' AS myValue, 'MyKey' AS keyField
) I
LEFT JOIN myTable T ON I.keyField = T.keyField
WHERE T.keyField IS NULL;
You are on the right path with IF NOT EXISTS. It is better to use IF NOT EXISTS() or IF EXISTS() than a Sub Query because SQL Server will stop scanning rows in the table when it finds the first instance that matches the EXISTS() condition your looking for. With a Sub Query written in the examples above it will scan the whole table.
A Classic example is the Insert or Update aka the SAVE.
IF EXISTS(SELECT * FROM Table_A WHERE Column_1 = #Parameter)
BEGIN
--Update Statement here.
END
ELSE
BEGIN
--Insert Statement here.
END
What about something like this:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF ##ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
Source