3

可能重复:
如何在 sqlserver 中转义单引号?

我在下面有一个脚本,可以从此链接删除数据库中的所有内容。当我在这条线上执行时它会出错。

SET @statement = '
IF(@type = 'F') or (@type = 'C') or (@type = 'D') or (@type='F') or (@type='K')

原因是因为单引号。我想知道如何解决这个错误?

/*** drop (pretty much) everything before rebuilding the database ***/
DECLARE
    OBJECTS CURSOR FOR SELECT
        so.name,
        so.type,
        so.type_desc,
        p.name AS parentName
    FROM
        sys.objects AS so
    LEFT JOIN sys.objects AS p ON so.parent_object_id = p.object_id
    WHERE
        so.schema_id = 1
    ORDER BY
        CASE
    WHEN so.type = 'F' THEN
        0
    WHEN so.type = 'TR' THEN
        1
    WHEN so.type = 'U' THEN
        2
    WHEN so.type = 'F' THEN
        3
    ELSE
        4
    END OPEN OBJECTS DECLARE
        @name AS nvarchar (MAX) DECLARE
            @type AS nvarchar (2) DECLARE
                @type_desc AS nvarchar DECLARE
                    @parentName AS nvarchar (MAX) DECLARE
                        @statement AS nvarchar (MAX) FETCH NEXT
                    FROM
                        OBJECTS INTO @name,
                        @type,
                        @type_desc,
                        @parentName
                    WHILE @@FETCH_STATUS = 0
                    BEGIN

                    SET @statement = '    IF(@type = ' F ')
BEGIN
PRINT ' DROPING FK : ' + @name + ' OF type ' + @type + ' (' + @type_desc + ') '
SET @statement = ' ALTER TABLE ' + @parentName + ' DROP CONSTRAINT ' + @name
EXECUTE(@statement)
END
ELSE IF (@type = ' TR ')
BEGIN
PRINT ' DROPING TRIGGER : ' + @name + ' OF type ' + @type + ' (' + @type_desc + ') '
SET @statement = ' DROP TRIGGER ' + @name
EXECUTE(@statement)
END
ELSE IF (@type = ' U ')
BEGIN
PRINT ' DROPING TABLE : ' + @name + ' OF type ' + @type + ' (' + @type_desc + ') '
SET @statement = ' DROP TABLE ' + @name
EXECUTE(@statement)
END
ELSE IF (@type = ' FN ')
BEGIN
PRINT ' DROPING FUNCTION : ' + @name + ' OF type ' + @type + ' (' + @type_desc + ') '
SET @statement = ' DROP FUNCTION ' + @name
EXECUTE(@statement)
END
ELSE
PRINT ' Didn 't drop object ' + @name + ' of type ' + @type + ' (' + @type_desc + ')'    FETCH NEXT
                    FROM
                        OBJECTS INTO @name,
                        @type,
                        @type_desc,
                        @parentName
                    END CLOSE OBJECTS DEALLOCATE OBJECTS
4

3 回答 3

6

如果您想在准备好的语句中使用单引号,请使用另一个单引号将其转义,例如,

SET @statement = 'world''s view';
SET @statement2 = 'world''s view';

从你上面的例子

SET @statement = '
                IF(@type = ''F'') or (@type = ''C'')  or
                  (@type = ''D'') or (@type=''F'') or
                  (@type=''K'')'

-- the strings are all red.
于 2012-11-15T04:53:01.440 回答
0

单引号用于表示 SQL 中的字符串文字。如果需要显式插入单引号,则应使用双单引号 ('')

于 2012-11-15T04:53:47.807 回答
0

它应该是这样的:

SET @statement = 'IF(@type = ''F'') or (@type = ''C'') or (@type = ''D'') or (@type=''F'') or (@type=''K'')'

拉吉

于 2012-11-15T04:58:19.077 回答