Home  >  Article  >  Database  >  关于quotename的用法

关于quotename的用法

WBOY
WBOYOriginal
2016-06-07 15:13:561432browse

首先,sqlserver里的标识符有一定的规则,比如 你 create table abc 123(...) 那么中间含有空格,它不是符合规则的。 你会写做 create table [abc 123](....) 即以[]来定界标识符。 quotename将 字串成为有效的标识符。 它有什么用呢? 我举个例子: 你有个

 

首先,sqlserver里的标识符有一定的规则,比如 你
create table abc 123(...)
那么中间含有空格,它不是符合规则的。

你会写做 create table [abc 123](....)
即以[]来定界标识符。

quotename将 字串成为有效的标识符。

它有什么用呢? 我举个例子:


你有个表名字叫做 aa[]bb

当某些应用动态语句查询时 你如何写呢
exec('select * from aa[]bb') ?X

set @sql='select * from ' + quotename('aa[]bb')
exec(@sql)

当然你也可以直接写出转义的写法

select * from [aa[]]bb]

也就是说,quotename 使函数中的输入成为一个有效的标识符。
比如上例中 aa[]bb 不是一个有效的标识符。

还有一点就是quotename函数有几种写法:
quotename('aa') 生成的有效的标识符为 [aa]
quotename('aa','') 生成的有效的标识符为 [aa]
quotename('aa','''') 生成的有效的标识符为 'aa'

 

解释2:

简单来说吧
比如你有一个表,名字叫 index
你有一个动态查询,参数是表名
declare @tbname varchar(256)
set @tbname='index'
---查这个表里的数据:
print('select * from '+@tbname)
exec('select * from '+@tbname)

--这样print出来的数据是
select * from index

因为index是字键字,肯定出错,加上括号就可以了:
select * from [index]

这便有了QUOTENAME,即:
print('select * from '+QUOTENAME(@tbname))
--结果:select * from [index]
exec('select * from '+QUOTENAME(@tbname))
 

参考自:http://www.cnblogs.com/smfish007bin/archive/2008/10/16/1312786.html

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn