【问题标题】:SQL Server 2012 Using Declared Variables in a JoinSQL Server 2012 在连接中使用声明的变量
【发布时间】:2013-12-03 03:08:17
【问题描述】:

我对 SQL Server 很陌生,所以希望这是有道理的 :)

我正在尝试声明要在 INNER JOIN 中使用的变量。

如果您看一下我的代码,您就会明白我正在尝试做什么,而无需我过多介绍。如果您需要更多信息,请告诉我。这种语法可能吗?

编辑:请参阅下面的新尝试

    --State - If suburb/postcode, could use postcode lookup
Declare @Missing as nvarchar(255),
 @MissingUpdate as nvarchar(255),
 @MatchA as nvarchar(255),
 @MatchB as nvarchar(255),
 @Reason as nvarchar(255);

Set @Missing = '[StateEXPORT]'; -- field to update
Set @MissingUpdate = '[State]'; -- field in postcode lookup to pull in
Set @MatchA = '[PostcodeEXPORT]'; -- field in master field to match with
Set @MatchB = '[Pcode]'; -- field in postcode lookup to match with
Set @Reason = 'Contactable - Needs verificiation - @MissingUpdate taken from Lookup'; -- reason here

update [BT].[dbo].[test]
set @Missing = b.@MissingUpdate,    
    FinalPot =  @Reason
FROM [BT].[dbo].[test] a
INNER JOIN [BT].[dbo].[Postcode Lookup] b
ON a.@MatchA = b.@MatchB
where (@Missing is null or @Missing = '0') and [AddressSource] != ('Uncontactable')
GO

编辑:第二次尝试:

set @sql = 'update [BT].[dbo].[test] set ' + quotename(@Missing) + '= b.' +     quotename(@MissingUpdate) + ', FinalPot = ' + @Reason + 'FROM [BT].[dbo].[test] a INNER JOIN [BT].[dbo].[Postcode Lookup] b ON a.' + quotename(@MatchA) + ' = b.' + quotename(@MatchB) + 'where (' + quotename(@Missing) + 'is null or' + quotename(@Missing) + ' = 0 and [AddressSource] != "(Uncontactable)"'

exec (@sql)

感谢您的帮助, 卢卡斯

【问题讨论】:

    标签: sql variables join sql-server-2012 declare


    【解决方案1】:

    不,这种语法是不可能的,至少不能直接:你需要指定列名,而不是具有名称的字符串变量。

    如果您希望动态决定列的名称,您可以创建一个代表您希望执行的语句的 SQL 字符串,并将该字符串传递给EXECUTE command。但是,您必须格外小心,不要将任何用户输入的数据放入生成的 SQL 字符串中,以避免SQL injection attacks。

    编辑:您第二次尝试可能失败的原因是您将方括号中的名称传递给quotename。您应该从变量声明中删除括号,如下所示:

    Set @Missing = 'StateEXPORT'; -- field to update
    Set @MissingUpdate = 'State'; -- field in postcode lookup to pull in
    Set @MatchA = 'PostcodeEXPORT'; -- field in master field to match with
    Set @MatchB = 'Pcode'; -- field in postcode lookup to match with
    

    【讨论】:

    • 啊,对。这是有道理的。我将尝试设置动态 SQL。不过我可能很快就会回到这里。干杯!
    【解决方案2】:

    你不能使用变量名作为没有动态 SQL 的列名。

    动态 SQL 查询示例:

    declare @ColumnName varchar(100) = 'col1'
    declare @sql varchar(max)
    set @sql = 'select ' + quotename(@ColumnName) + ' from dbo.YourTable'
    exec (@sql)
    

    【讨论】:

    • 听起来不错。我会有一个裂缝。很快再见(希望不会)
    • @Lucas:动态 SQL 是字符串操作的问题,这在 C# 等客户端语言中通常更容易。祝你好运!
    猜你喜欢
    • 2015-12-12
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2015-04-04
    • 2014-05-14
    • 1970-01-01
    相关资源
    最近更新 更多