我想使用游标删除数据库(sql server 2008 r2)的所有同义词。environment-database name-'mydatabase',schema name-'dbo'..你能像我尝试的那样指导我吗,但是while .. end的语句不能删除同义词。什么逻辑应该应用 wrt 游标?
问问题
7954 次
2 回答
18
无需使用游标。按照设置执行:
declare @n char(1)
set @n = char(10)
declare @stmt nvarchar(max)
select @stmt = isnull( @stmt + @n, '' ) +
'drop synonym [' + SCHEMA_NAME(schema_id) + '].[' + name + ']'
from sys.synonyms
exec sp_executesql @stmt
于 2011-07-20T19:47:29.753 回答
3
Similar to Jason's answer with some improvements
- Use Quotename() function to wrap the names in square brackets
- Initialize the @SQL variable to an empty string, this means that the isnull is not required, and means that when you concatenate the results of the query into a single string it doesn't get the type wrong. String literals in a concatenation can take the default nvarchar size and cause your resulting string to be truncated unexpectedly.
- Ensure the string literals are also nvarchar by using the N in front of them.
- Filter to the dbo schema only, as the OP requested.
- Add the sys schema to the sp_executesql call
Totally agree this is not something where you need a cursor.
DECLARE @SQL NVARCHAR(MAX) = N''
SELECT @SQL += N'DROP SYNONYM ' + QUOTENAME(SCHEMA_NAME([schema_id])) + N'.' + QUOTENAME(name) + N';' + Char(13) + Char(10)
FROM sys.synonyms
WHERE SCHEMA_NAME([schema_id]) = N'dbo'
EXEC sys.sp_executesql @SQL
于 2015-02-18T00:09:31.157 回答