用于查询 Adventureworks 表的动态 SQL

发布于 2024-08-28 02:03:50 字数 552 浏览 8 评论 0原文

我试图从 Sql Server 2008 中的“Person”模式查看 Adventureworks DB 中的表列表。我开发了以下 SP,但按如下方式运行后,出现错误“')' 附近的语法不正确”。你知道我如何修改这个 SP 或 exec 语句吗?

CREATE PROCEDURE [getTableNames]
@SchemaName VARCHAR(50)
AS

BEGIN
SET NOCOUNT ON;
SET @SchemaName = 'PERSON'
DECLARE @cmd AS VARCHAR(max)
SET @SchemaName = RTRIM(@SchemaName)
SET @cmd = N'SELECT TABLE_NAME ' + 
'FROM information_schema.Tables ' +
'WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_SCHEMA = @SchemaName'
END

exec sp_executesql getTableNames, N'@SchemaName NVARCHAR(50), @SchemaName'

I am trying to see a list of tables from Adventureworks DB from "Person" schema in Sql Server 2008. I developed the following SP, but after running it as follows it gives me error "Incorrect syntax near ')'". Do you know how I can revise this SP or exec statement?

CREATE PROCEDURE [getTableNames]
@SchemaName VARCHAR(50)
AS

BEGIN
SET NOCOUNT ON;
SET @SchemaName = 'PERSON'
DECLARE @cmd AS VARCHAR(max)
SET @SchemaName = RTRIM(@SchemaName)
SET @cmd = N'SELECT TABLE_NAME ' + 
'FROM information_schema.Tables ' +
'WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_SCHEMA = @SchemaName'
END

exec sp_executesql getTableNames, N'@SchemaName NVARCHAR(50), @SchemaName'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笑梦风尘 2024-09-04 02:03:50

您实际上不需要在这里使用动态 SQL,而且您的存储过程不太正确,因为您没有执行 @cmd 语句。只需使用:

CREATE PROCEDURE [getTableNames]
@SchemaName VARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON
    SELECT TABLE_NAME 
    FROM information_schema.Tables
    WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = @SchemaName
END

EXECUTE getTableNames 'PERSON'

You don't actually need to use dynamic SQL here, plus your sproc isn't quite right as you're not executing the @cmd statement. Just use:

CREATE PROCEDURE [getTableNames]
@SchemaName VARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON
    SELECT TABLE_NAME 
    FROM information_schema.Tables
    WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = @SchemaName
END

EXECUTE getTableNames 'PERSON'
双手揣兜 2024-09-04 02:03:50

您不需要动态 SQL:

select * from sys.tables
where type_desc = 'BASE TABLE' and schema_id = schema_id(@SchemaName)

You don't need dynamic SQL:

select * from sys.tables
where type_desc = 'BASE TABLE' and schema_id = schema_id(@SchemaName)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文