为每列添加前缀

时间:2019-01-07 20:33:43

标签: sql sql-server

我有这张桌子,它是列的名称:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="smallCatalogWrap">
  <div class="smallCatalogBlock" data-availability="Yes">
    <span class="smallCatalogTitle">A</span>
    <div class="smallCatalogButtonWrap">
      <div class="catalogSmallCircle"></div>
    </div>
  </div><div class="smallCatalogBlock comingSoonSmall" data-availability="No">
    <span class="smallCatalogTitle">B</span>
    <div class="smallCatalogButtonWrap">
      <div class="catalogSmallCircle"></div>
    </div>
  </div><div class="smallCatalogBlock comingSoonSmall" data-availability="No">
    <span class="smallCatalogTitle">C</span>
    <div class="smallCatalogButtonWrap">
      <div class="catalogSmallCircle"></div>
    </div>
  </div>
</div>

我想为每列添加一个前缀,如下所示:

Name, Birthday, Year, Size

很明显,我的列多于这4列,所以这就是为什么我要查询的原因-如何在SQL Server中为列名添加前缀?

非常感谢! :)

2 个答案:

答案 0 :(得分:0)

一种想法是使用以下过程sp_rename (Transact-SQL)

从表目录(在sys.objects类型为'U'的目录中选择名称)生成脚本。

例如:

USE DB;  
GO  
EXEC sp_rename 'Table.Name', 'NY_Name', 'COLUMN';  
GO  

答案 1 :(得分:0)

获得它的一种方法是使用动态SQL,但如果可以帮助的话,请尽量避免这样做。

这是一种方法:

/* --create table to test

CREATE TABLE dbo.WTF (
    Name VARCHAR(10), 
    Birthday VARCHAR(10), 
    Year VARCHAR(10), 
    Size VARCHAR(10)
)

*/

DECLARE @prefix VARCHAR(10) = 'NY_'

DECLARE @sql NVARCHAR(1000) = N'';
DECLARE @columns VARCHAR(1000) = '';

SELECT  @columns = @columns + c.name + ' ' + QUOTENAME(@prefix + c.name) + ',
'
FROM sys.tables t
INNER JOIN sys.columns c 
ON t.object_id = c.object_id
WHERE t.name = 'WTF'
ORDER BY c.column_id

set @columns = left(@columns, len(@columns) - 3) --remove last comma and cr lf

set @sql = N'SELECT
' + @columns + '
FROM dbo.WTF'

select @sql

exec sp_executesql @sql

这将返回:

SELECT
Name [NY_Name],
Birthday [NY_Birthday],
Year [NY_Year],
Size [NY_Size]
FROM dbo.WTF

NY_Name    NY_Birthday NY_Year    NY_Size
---------- ----------- ---------- ----------

祝你好运!