0

Simple question - If I'm trying to build a dynamic query and run it in a PL/SQL Stored Procedure, how do I enclose the variable in single quotes so that it is called correctly?

For example:

I first declare a variable to hold a cursor's column value. I also declare a variable to hold the dynamic query:

vTest VARCHAR(200);
l_cur_string VARCHAR2(128);

After defining my cursor, I loop through it like so:

For entry in c1
LOOP
vTest:= entry.variable;

 l_cur_string := 'SELECT ex1, ex2FROM exTable WHERE col1= || vTest;
END LOOP;

Of course, when I print out the dynamic query, it doesn't have the single quotes around vTest. I've tried adding them, but nothing I do compiles correctly.

Any help for a simple question? Thanks!

4

2 回答 2

8

将要出现在字符串中的单引号加倍:

l_cur_string := 'SELECT ex1, ex2FROM exTable WHERE col1= '''|| vTest || '''';

但请记住,直接在 SQL 表达式中嵌入字符串是一种快速利用的途径。

于 2013-06-04T15:28:45.780 回答
1

试试这两个片段

    声明 @sqlCommand varchar(1000)
    声明 @columnList varchar(75)
    声明@city varchar(75)
    SET @columnList = '客户 ID、联系人姓名、城市'
    SET @city = '''伦敦'''
    SET @sqlCommand = 'SELECT' + @columnList +' FROM customers WHERE City = ' + @city
    打印@sqlCommand
    --执行(@sqlCommand)


    声明 @sqlCommand nvarchar(1000)
    声明 @columnList varchar(75)
    声明@city varchar(75)
    SET @columnList = '客户 ID、联系人姓名、城市'
    SET @city = '伦敦'
    SET @sqlCommand = 'SELECT' + @columnList +' FROM customers WHERE City = @city'
    打印@sqlCommand
    --EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

于 2013-06-04T15:28:21.577 回答