conditional insert in ms-access
How can we conditionally insert a record in开发者_StackOverflow an MS-ACCESS Table. I am trying the following but it is giving me error. Note:This is a stored query.
PARAMETERS [@Value1] Long, [@Value2] Text ( 255 ), [@Value3] DateTime, [@Value4] DateTime;
INSERT INTO tblTest ( Field1, Field2, Field3, Field4)
SELECT [@Value1] AS expr1, [@Value2] AS expr2, [@Value3] AS expr3, [ @Value4] AS expr4
WHERE (((Exists (Select * from tblTest where Field2=@Value2 and Field3=@Value3 and Field4=@Value4))=False));
In Access, if you have a WHERE clause, you have to have a FROM clause, which means you have to include a table in your query even if you don't use any values from the table. So, the only way I know to make this work is to add a dummy table to your database that has just one row in it. It doesn't matter what columns/data types it has. In my example I called it ATable:
PARAMETERS [@Value1] Long, [@Value2] Text ( 255 ), [@Value3] DateTime, [@Value4] DateTime;
INSERT INTO tblTest ( Field1, Field2, Field3, Field4)
SELECT [@Value1] AS expr1, [@Value2] AS expr2, [@Value3] AS expr3, [ @Value4] AS expr4
FROM ATable
WHERE (((Exists (Select * from tblTest where Field2=@Value2 and Field3=@Value3 and Field4=@Value4))=False));
This is a kludge, and an ugly one that will start inserting duplicate records as soon as someone decides to add another row to ATable. Because of that, it would be better to use an If/Then to decide whether to run the query at all.
精彩评论