我想在ms access 2007数据库查询中声明和设置变量。我想将2个数据库查询结果存储在2个变量中,因为它们在执行后是整数或字符串类型。我想知道如何声明和设置变量?
等效的SQL服务器将是这样的
declare @var1 varchar(50)
set @var1 = 'select * from table'
答案 0 :(得分:2)
Jet / ACE SQL中不支持此语法。根据您的最终目标,您需要使用VBA(下面提供的示例)或子查询(如@ Thomas的解决方案)来实现此类功能。
以下几行(改编自Allen Browne's website):
Function DAORecordsetExample()
'Purpose: How to open a recordset and loop through the records.'
'Note: Requires a table named MyTable, with a field named MyField.'
Dim rs As DAO.Recordset
Dim strSql As String
strSql = "SELECT MyField FROM MyTable;"
Set rs = CurrentDb.OpenRecordset(strSql)
Do While Not rs.EOF
Debug.Print rs!MyField
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
End Function
答案 1 :(得分:2)
如果“在一个查询中”你的意思是“不诉诸VBA例程”,那就更难了。最简单的解决方案是单个查询,然后在主查询中使用。获取值的查询可能如下所示:
Select SomeCol As Var1
, ( Select SomeOtherCol
From SomeOtherTable ) As Var2
From SomeTable
以上假设子查询将返回单行,并且我们得到一行Var1的值。如果不能保证,那么你会想要使用外部查询保证返回一行,如下所示:
Select (Select SomeCol
From SomeTable ) As Var1
, ( Select SomeOtherCol
From SomeOtherTable ) As Var2
From AnotherTableWithAtLeastOneRow
Where Col = "SomeValueToGetOneRow"
您可以将其保存为查询定义,然后在主查询中使用它。