我想创建一个代码,它将返回一个表中的所有列名,我可以将其用于其他目的。我写了这段代码。
DECLARE @SQLCommand VARCHAR(4000)
DECLARE @TableName VARCHAR(50)
SET @TableName = 'ship_to_ud'
SET @SQLCommand =
'DECLARE @SelTable VARCHAR(50)
SET @SelTable = ' + '''' + @TableName + '''' + '
SELECT
tables.name AS TableName
,all_columns.name AS ColumnName
FROM sys.all_columns
INNER JOIN sys.tables ON sys.all_columns.object_id = sys.tables.object_id
INNER JOIN sys.types ON sys.all_columns.user_type_id =
sys.types.user_type_id
WHERE sys.tables.name = @SelTable
ORDER BY all_columns.name'
EXEC(@SQLCommand)
我想添加一个显示TableName.ColumnName的列,但语法不合理我。任何帮助将不胜感激。 提前谢谢。
答案 0 :(得分:2)
不需要动态SQL
DECLARE @TableName VARCHAR(50)
SET @TableName = 'Sample_Table'
SELECT t.TABLE_NAME, c.COLUMN_NAME, TABLE_COLUMN = t.TABLE_NAME+'.'+c.COLUMN_NAME
FROM INFORMATION_SCHEMA.tables t
CROSS JOIN INFORMATION_SCHEMA.COLUMNS c
WHERE t.TABLE_NAME = @TableName
AND c.TABLE_NAME = @TableName;
结果:
TABLE_NAME COLUMN_NAME TABLE_COLUMN
----------------- ------------- ----------------------------
Sample_Table Incident Sample_Table.Incident
Sample_Table Location Sample_Table.Location
Sample_Table Order_Num Sample_Table.Order_Num
Sample_Table Item Sample_Table.Item
Sample_Table Shift Sample_Table.Shift
Sample_Table Team_Member Sample_Table.Team_Member
Sample_Table Team_Mem_ID Sample_Table.Team_Mem_ID
请注意,我使用的是本地名为"样本表的表格。"另请注意,我没有解决表格的架构,但是,如果你查看我使用的表格(还有一些提供此信息的系统表格),那将很容易弄清楚。
答案 1 :(得分:2)
我同意Alan Burstein的说法,这里不需要动态的SQL。我个人更喜欢转到sys表,因为information_schemas并不总是最新的,我永远不会记得哪些是哪些,哪些不是。 https://sqlblog.org/2011/11/03/the-case-against-information_schema-views
DECLARE @TableName SYSNAME
SET @TableName = 'YourTableName'
select TableName = t.name
, ColumnName = c.name
, FullName = t.name + '.' + c.name
from sys.tables t
join sys.columns c on c.object_id = t.object_id
where t.name = @TableName
答案 2 :(得分:0)
试试这个
strVendor = Nz(DLookup("Vendor", "PurchaseOrder", strFilter), "None")