Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 意外的字符串连接结果_Sql Server_Sql Server 2008_Tsql - Fatal编程技术网

Sql server 意外的字符串连接结果

Sql server 意外的字符串连接结果,sql-server,sql-server-2008,tsql,Sql Server,Sql Server 2008,Tsql,设想以下模式: create table tempdb..t1 (id int, name sysname); create table tempdb..t2 (id int, name sysname); create index IX1 on tempdb..t1 (id); create index IX2 on tempdb..t2 (id); 现在我尝试编写索引定义脚本: declare @stmt nvarchar(max) = ''; select @stmt += 'cr

设想以下模式:

create table tempdb..t1 (id int, name sysname); 
create table tempdb..t2 (id int, name sysname); 
create index IX1 on tempdb..t1 (id); 
create index IX2 on tempdb..t2 (id);
现在我尝试编写索引定义脚本:

declare @stmt nvarchar(max) = '';
select @stmt += 'create index ' + ix.name + ' on ' + t.name 
    + isnull(' where ' + ix.filter_definition, '') + char(13)
    from tempdb.sys.tables t
    join tempdb.sys.indexes ix on t.object_id = ix.object_id
    where ix.type > 0 and t.name in ('t1','t2')
    order by ix.name;
print @stmt;
我希望得到两个索引定义:

create index IX1 on t1
create index IX2 on t2
但只获得第二名。如果我删除ORDERBY或isnull部分,或添加top语句,我将得到这两个定义


我是否遗漏了一些明显的内容?

当使用select将值放入标量变量时,该变量中只会放入一行。它不会聚合您的两行,也不会聚合结果集到一行中的大小

假设你有一个整数变量,你试图给它分配700个不同的值,那是行不通的。尝试将两个字符串赋给同一个变量也是一样的。相反,将只使用一个值

declare @i int;

SELECT @i = t.value
FROM myTable AS t
WHERE t.value between 1 and 700

SELECT @i
创建伪字符串连接聚合函数的一个好方法是使用FOR XML PATH的XML功能。 查看此问题:

我大吃一惊这种行为是故意的

总结一下Martin链接中的信息:不要像这样进行连接。即使没有制造商的订单,也不能保证它能正常工作。 要获得保证有效的结果,请使用for xml

声明@stmt nvarcharmax=; 选择@stmt=select 在“+t.name”上创建索引“+ix.name+” +isnull'其中'+ix.filter_定义,+char10 来自tempdb.sys.t表 在t.object\u id=ix.object\u id上连接tempdb.sys.index ix 其中,ix.type>0,t.name位于't1','t2' 按姓名排序 用于xml路径; 打印@stmt;
其他选项是使用游标或SQLCLR

这种连接方法不能保证有效。如果我删除ORDERBY子句,请参阅聚合工作的可能重复。但正确的结果并不能保证。看看Martin的链接。我想我需要仔细阅读连接。我认为它在2008 R2上根本不起作用。