问题
I have read this entry (http://stackoverflow.com/questions/8513185/vbscript-to-correctly-re-format-a-delimited-text-file) many times and still do not understand the .Execute section.
WScript.Echo oTDb.Execute(Replace("SELECT * FROM [@T]", "@T", sTbl1)) _
.GetString( adClipString, , "|", vbCrLf, "" )
The pieces I am having trouble with are the [@T] and "@T".
I know it is the "@T" that is reading the filename in the schema file and and the [@T] must be using the "@T" as a substitute. What I cannot find out is where this is mentioned/spoken about.
Some addition questions I have are: 1. If the filename can be substituted with a variable then what else can? 2. What are the rules for maintaining variables Do they have to start with the @ symbol Are there any reserved words If they have to start with the @ symbol, does the next character have to be a letter
回答1:
As I am responsible for @Milton's worry/puzzlement:
There is no variable interpolation/substitution in VBScript. Other languages - e.g. Perl - will splice variables or even expression results into string literals when you mark the replacements with special symbols. No such funny letters in VBScript.
SQL dialects allow parameterized commands in which parts to be replaced are marked by ? and/or names prefixed by symbols like @. But here ADO never sees the @T - VBScript's Replace() function has interpolated the table name before the resulting strings is send to .Execute().
Building complex strings from parts (SQL statements, commandlines for .Run or .Exec, ...) by concatenation is cumbersome. The most important drawback is that you can't (proof) read the string anymore for all those " and &.
A simple workaround is to use Replace(), as in
[sResult = ] Replace("SELECT * FROM [@T]", "@T", sTbl1)
I used the @ just for letting the placeholder stand out. As you would have to stack/nest the Replace() calls when you need more substitutions on the template, other strategies are worth considering:
- writing a function that takes a template string and a dictionary of replacements to apply Regexp.Replace() to the string
- using .NET's System.Text.StringBuilder and its .AppendFormat to do the slicing in a sprintf like style
来源:https://stackoverflow.com/questions/14423385/vbscript-sql-select-query-clarification-and-variable-substitution