Reputation: 611
I am trying to create a TableAdapter
for a typed DataSet for my persistence layer. I am going to read information from a file, and then insert that into the database.
The SerialNumber
is related to a MonitorID
in the database. The insert I am trying to write in the TableAdapter
Config Wizard in Visual Studio is:
INSERT INTO VOCReading (MonitorID, Level, Date, Time, Accuracy)
VALUES( (SELECT MonitorID FROM Monitor WHERE SerialNumber= @SerialNumber), @Level, @Date, @Time, @Accuracy)
The error I get is
Must declare the scalar variable '@SerialNumber'
How can I get around this? SerialNumber
is in the Monitor
table, but the table I need to insert into is VOCReading
.
Upvotes: 1
Views: 480
Reputation: 755128
The INSERT
command comes in two flavors:
(1) either you have all your values available, as literals or SQL Server variables - in that case, you can use the INSERT .. VALUES()
approach:
INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN)
VALUES(Value1, Value2, @Variable3, @Variable4, ...., ValueN)
Note: I would recommend to always explicitly specify the list of column to insert data into - that way, you won't have any nasty surprises if suddenly your table has an extra column, or if your tables has an IDENTITY
or computed column. Yes - it's a tiny bit more work - once - but then you have your INSERT
statement as solid as it can be and you won't have to constantly fiddle around with it if your table changes.
(2) if you don't have all your values as literals and/or variables, but instead you want to rely on another table, multiple tables, or views, to provide the values, then you can use the INSERT ... SELECT ...
approach:
INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN)
SELECT
SourceColumn1, SourceColumn2, @Variable3, @Variable4, ...., SourceColumnN
FROM
dbo.YourProvidingTableOrView
Here, you must define exactly as many items in the SELECT
as your INSERT
expects - and those can be columns from the table(s) (or view(s)), or those can be literals or variables. Again: explicitly provide the list of columns to insert into - see above.
You can use one or the other - but you cannot mix the two - you cannot use VALUES(...)
and then have a SELECT
query in the middle of your list of values - pick one of the two - stick with it.
So in your case, you'd have to use the INSERT .. SELECT
approach since you need to select something from a table - you cannot use the VALUES
approach:
INSERT INTO VOCReading (MonitorID, Level, Date, Time, Accuracy)
SELECT MonitorID, @Level, @Date, @Time, @Accuracy
FROM Monitor
WHERE SerialNumber = @SerialNumber
Upvotes: 1